How to Create Custom Exception in Java


The example is to show how to create a Custom exception class by extending its class in Java.

Source Code

1 exception class)

package com.beginner.examples;


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

}

2)

package com.beginner.examples;

public class TestCustomException {

	public static void main(String[] args) {

		int a = 10;
		int b = -2;
		try {
			//Using this method requires a try catch
			div(a, b);
		} catch (DivByNegativeException e) {
			System.out.println(e.getMessage());
			e.printStackTrace();
		}

	}

	public static int div(int a, int b) throws DivByNegativeException {
		//If b is less than 0 we throw this exception
		if (b < 0) {
			
			throw new DivByNegativeException("Divided by the negative Exception");
		}
		return a / b;
	}

}

Output:

Divided by the negative Exception
com.beginner.examples.DivByNegativeException: Divided by the negative Exception
	at com.beginner.examples.TestCustomException.div(TestCustomException.java:23)
	at com.beginner.examples.TestCustomException.main(TestCustomException.java:11)
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments