Home Tutorial Java Core Exception Handling : Custom Exception

 
 

Exception Handling : Custom Exception
Posted on: November 20, 2012 at 12:00 AM
Advertisement
In this tutorial, we will discuss about the Custom Exceptions(user defined exceptions).

Exception Handling : Custom Exception

In this tutorial, we will discuss about the Custom Exceptions(user defined exceptions).

Custom Exception : Custom exception is simply a user-defined exception. You have studied about several inbuilt exceptions but sometimes application requires some meaningful exceptions to develop. So, we can create our own exceptions by extending Exception class. These custom exception can be thrown using the keyword 'throw' whenever the corresponding condition occurs.

Example :

class MyException extends Exception {
public MyException(String message) {
super(message);
}
}

class CustomException {
public static void main(String[] args) throws Exception {
for (int i = 1; i < 5; i++) {
System.out.println("i = " + i);
if (i == 3) {
throw new MyException("My Exception occurred");
}
}
}
}

Description : In this example, we have created a class MyException that shows custom exception.We have created a for loop that iterate numbers from 1 to 5, whenever loop points to number 3, the custom exception will be thrown using the 'throw' keyword. You can display any message and any logic to show custom exceptions.

Output :

i = 1
i = 2
i = 3
Exception in thread "main" MyException: My Exception occurred
at CustomException.main(CustomException.java:12)

 

Advertisement

Related Tags for Exception Handling : Custom Exception :


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: November 20, 2012

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com