Create Custom Exception Class in Java

Category: Java   Tags: Java, Java Basic, Java Exception Handling, Java Custom Exception

Here I will show you how to create a custom Java exception class. If you want to know more about Java exception, go here Java Exception Handling.

By making a subclass of Exception class you can create a custom exception in Java. Exception class inherit all methods provided by Throwable, therefore all exception class including your custom exception class can use all methods provided by Throwable.

JavaCustomExceptionExample.java

                          package com.tutorial.javabasic;

                          class MyException extends Exception {

                              private String description;
                              public MyException(String str) {
                                  description = str;
                              }

                              public String toString() {
                                  return "MyException: " + description;
                              }

                          }

                          public class JavaCustomExceptionExample {

                              public static void main(String s[]) throws MyException {
                                  int a = 100;
                                  if(a < 1000)
                                      throw new MyException("a is less than 1000");
                              }
                          }
                        

Output:

                          Exception in thread "main" MyException: a is less than 1000
                            at com.tutorial.javabasic.JavaCustomExceptionExample.main(JavaCustomExceptionExample.java:21)
                        

Overriding toString() allows you to format exception description in your way.