No announcement
 

User Defined Exceptions

Java defines most of the exception, but sometimes there are scenarios where we need to define our own custom exceptions. We can create custom exception by extending Exception class.

Example:

UserDefinedExceptionDemo.java

package com.codingnous.tutorial;

public class UserDefinedExceptionDemo {

	public static void main(String args[]) {
		try {
			// Throw user defined exception
			throw new MyException("Invalid operation");
		} catch (MyException ex) {
			System.out.println("Exception occurred!");

			// Print exception message
			System.out.println(ex.getMessage());
		}
	}

}

class MyException extends Exception {

	private static final long serialVersionUID = 1L;

	public MyException(String s) {
		// Invoke constructor of Exception class
		super(s);
	}
}

Output
Exception occurred! Invalid operation