Mazzy Mazzy - 1 month ago 11
Java Question

How to create a custom exception type in Java?


Possible Duplicate:

How can I write an Exception by myself?




I 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

Answer

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
 }