Java Programming

11.3 Custom Exception

Custom exceptions in java are also known as User defined exceptions.
Most of the times when we are developing java program, we often feel a need to use our own exceptions. These exceptions are known as Custom exceptions or User defined.

We can create our own exception sub class simply by extending java Exception class.
We can define a constructor for our Exception sub class (not compulsory) and can override the toString() function to display our customized message on catch.

class MyException extends Exception{
String str;
MyException(String str) {
this.str=str;
}
public String toString(){
return (“message = “+str);
}
}

class CustomException{
public static void main(String args[]){
try{
throw new MyException(“HELLO”);
}
catch(MyException e){
System.out.println(e);
}
}
}

Output:
message= HELLO

Note:
1. User defined exception needs to inherit (extends) Exception class in order to act as an exception.
2. throw keyword is used to throw such exceptions.
3. You can have a Constructor if you want.
4. You can override the toString() function, to display customized message.

Download for more knowledge

https://play.google.com/store/apps/details?id=ab.java.programming

Leave a comment