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.


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


class MyException extends Exception {

	private static final long serialVersionUID = 1L;

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

Exception occurred! Invalid operation