Example & Tutorial understanding programming in easy ways.

How to write custom exception in Java?

We can extend Exception class or any of it’s subclasses to create our custom exception class. The custom exception class can have it’s own variables and methods that we can use to pass error codes or other exception related information to the exception handler.

A simple example of custom exception is shown below.

class WordContainsException extends Exception
      //Parameterless Constructor
      public WordContainsException() {}

      //Constructor that accepts a message
      public WordContainsException(String message)

try { if(word.contains(" ")) { throw new WordContainsException(); } } catch(WordContainsException ex) { //Process message however you would like }

Read More →