Site icon

Create custom or user defined unchecked exception in java (example)

Exception class hierarchy in java

Fig 1: Custom NullPointerException & ArithmeticException

Program – Custom user defined arithmetic & nullpointer exception

1.) CustomArithmeticException Class: 

package org.learn.exception;

public class CustomArithmeticException extends ArithmeticException {

	private static final long serialVersionUID = 652325545058196579L;

	public CustomArithmeticException(String s) {
		super(s);
	}
}

2.) CustomNullPointerExceptionClass: 

package org.learn.exception;

public class CustomNullPointerException extends NullPointerException {

	private static final long serialVersionUID = 5627096569547521249L;

	public CustomNullPointerException(String s) {
		super(s);
	}
}

3.) ExceptionClient Class:

package org.learn.client;

import org.learn.exception.CustomArithmeticException;
import org.learn.exception.CustomNullPointerException;

public class ExceptionClient {
	public static void main(String[] args) {

		// 1. Throw & catch ArithmeticException
		try {
			simulateArithmeticException();
		} catch (CustomArithmeticException exp) {
			System.out.println("1. Caught MyArithmeticException:"+exp.getMessage());
		}

		// 2. Throw & catch NullPointerException		
		try {
			simulateNullPointerException();
		} catch (CustomNullPointerException exp) {
			System.out.println("2. Caught MyNullPointerException : "+exp.getMessage());
		}
	}
	
	private static void simulateArithmeticException() {
		int divByZero = 0;
		try {
			divByZero = 100 / 0;
			System.out.println("divByZero value:"+divByZero);
		} catch (ArithmeticException exp) {
			throw new CustomArithmeticException("ArithmeticException occurred : " + exp.getMessage());
		}
	}
	
	@SuppressWarnings("null")
	private static void simulateNullPointerException() {
		try {
			String blankString = null;
			System.out.println("String length :"+blankString.length());
			//simulating null pointer exception.
		} catch (NullPointerException exp) {
			throw new CustomNullPointerException("NullPointerException occurred ");
		}
	}
}

Output – Custom user defined arithmetic & nullPointer exception

1. Caught MyArithmeticException:ArithmeticException occurred : / by zero
2. Caught MyNullPointerException : NullPointerException occurred 

Download code – Custom User defined /Unchecked exception

 

Exit mobile version