Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (10.2k points)

 would like to create a custom exception in Java, how do I do it?

...

try{

...

String word=reader.readLine();

if(word.contains(" "))

  /*create custom exception*/

}

catch(){

When I create my custom exception with throw new..., I obtain the error unreported exception...must be caught or declared to be thrown

1 Answer

0 votes
by (46k points)

You should be able to create a custom exception class that extends the Exception class, for example:

class WordContainsException extends Exception

{

      // Parameterless Constructor

      public WordContainsException() {}

      // Constructor that accepts a message

      public WordContainsException(String message)

      {

         super(message);

      }

 }

Usage:

try

{

     if(word.contains(" "))

     {

          throw new WordContainsException();

     }

}

catch(WordContainsException ex)

{

      // Process message however you would like

}

Related questions

0 votes
1 answer
asked Oct 28, 2019 in Java by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...