Java Custom exception

Custom exception:

 

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

Note:
1. For writing custom-checked exceptions, extend the Exception class.
2. For writing custom unchecked exceptions, extend the RuntimeException class.

Java Custom Exception Example

 

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
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);
}
}
}
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); } } }
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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
com.w3schools.business.MyException: This is a custom exception.
com.w3schools.business.MyException: This is a custom exception.
com.w3schools.business.MyException: This is a custom exception.