How to create your own exception in java – 2020

Create your own exception in java

If you want to create your own exception to handle situations specific to your application. You should define a subclass of Exception to create your own exception in java.

The Exception class does not define any methods of its own. It does, of course, inherit those methods provided by Throwable. Thus all exceptions, including those that you create, have methods defined by Throwable.

Exception Handling in explanation https://notesforgeeks.com/exception-handling/

Creating own exception program:

// This program creates a custom exception type.
class MyException extends Exception {
private int detail;
 
MyException(int a) {
detail = a;
}
public String  toString() {
return "myException["+detail+"]";
}
  }
Class ExceptionDemo {
static void compute(int a) throws MyException {
System.out.println("Called compute(" + a+")");
if(a>10)
throw new MyException(a);
System.out.println("Normal exit");
}
public static void main(String args[]) {
try {
compute(1);
compute(30);
}  catch(MyException e) {
System.out.println("Caught " + e);
    }
 }
}

Output:
Called compute(1)
Normal exit
Called compute(30)
Caught MyException[30]
Follow me on Instagram Page CLICK HERE
Follow me on Facebook Page CLICK HERE

Leave a comment