Custom Exception in Java

Custom Exception in Java can be created by Extending the Exception Class. By Creating Custom Exception in Java We can Provide Some Custom Information.

Program to Create Custom Exception in Java:-

public class TestCustomException {

	public static void main(String[] args) throws CustomException{
		int number = 0;
		try{
			System.out.println("program to create custom exception in java");
			checkException(number);
		}
		catch(CustomException cex){
			System.out.println(cex.getMessage());
		}
	}

	static void checkException(int number) throws CustomException{
		if(number == 0){
			throw new CustomException("number can not be zero");
		}
		else{
			System.out.println("number is valid");
		}
	}

}

class CustomException extends Exception{

	private static final long serialVersionUID = 1L;

	private String exception = null;

	public CustomException(){
		super();
	}

	public CustomException(String exception){
		super(exception);
		this.exception=exception;
	}

	public String getException(){
		return exception;
	}

	public String toString(){
		return exception;
	}
}

output:-
custom exception in java

Leave a Comment