CodesJava

Easy learning with example program codes

Custom exception in java


Custom exception:

You can define your own exception also. These exceptions are known as custom exceptions.

Note:
1. For writing custom checked exception, extend Exception class.
2. For writing custom unchecked exception, extend RuntimeException class.

Example:

CustomExceptionExample.java

/**
 * This program is used to create custom exception.
 * @author codesjava
 */
class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}
 
class Test{
	public void display() throws MyException {
	  throw new MyException("This is a custom exception.");
	}
}
 
public class CustomExceptionExample {
	public static void main(String args[]){
		//creating Test object.
		Test obj = new Test();
 
		//method call.
		try{
			obj.display();
		}catch(Exception e){
			System.out.println(e);
		}
	}
}

Output:

com.codesjava.business.MyException: This is a custom exception.

Download this example.
 
Next Topic: Commonly used exception methods of Throwable class in java.
Previous Topic: Exception handling with method overriding in java.

Related Topics:

Some important terms for Exception Handling.
Exception handling in java.
try and catch blocks in java with example.
Multiple catch blocks in java with example.
Nested try block in java with example.
Finally in java with example.
throw in java with example.
throws in java with example.
Exception propagation in java with example.
Exception handling with method overriding in java.
Custom exception in java with example.
Commonly used exception methods of Throwable class in java.

 

Please follow and like us:
Posted in Java   

Core Java Tutorial



Copyright © 2019 CodesJava DMCA.com Protection Status SiteMap Reference: Java Wiki