Java

Java – User Defined Exception

Classes for exceptions like ArithmeticException and NullPointerException have previously been introduced in Java. In the last session, we learned how to explicitly throw these exceptions depending on your requirements using the throw keyword. These exceptions are already configured to occur on pre-defined situations, such as when you divide a number by zero it triggers ArithmeticException.

In Java, we may create our own exception classes and use the throw keyword to raise those exceptions. These exceptions are referred to as custom or user-defined exceptions. In this article, we’ll show you how to build your own custom exception and throw it in response to a certain circumstance.

You need have a basic understanding of Java’s throw and try-catch blocks in order to comprehend this lesson.

Example of User defined exception in Java

/* This is my Exception class, I have named it MyException
 * you can give any name, just remember that it should
 * extend Exception class
 */
class MyException extends Exception{
   String str1;
   /* Constructor of custom exception class
    * here I am copying the message that we are passing while
    * throwing the exception to a string and then displaying 
    * that string along with the message.
    */
   MyException(String str2) {
	str1=str2;
   }
   public String toString(){ 
	return ("MyException Occurred: "+str1) ;
   }
}

class Example1{
   public static void main(String args[]){
	try{
		System.out.println("Starting of try block");
		// I'm throwing the custom exception using throw
		throw new MyException("This is My error Message");
	}
	catch(MyException exp){
		System.out.println("Catch Block") ;
		System.out.println(exp) ;
	}
   }
}

Output:

Starting of try block
Catch Block
MyException Occurred: This is My error Message

Explanation:

You can notice that I included a string in parentheses when I threw a custom exception (throw new MyException(“This is My error Message”);). That is why my unique exception class has a parameterized constructor (with a String argument).

Notes:
1. Exception class must extend User-DefinedException.
2. The throw keyword is used to throw the exception.

Another Example of Custom Exception

In this illustration, a method’s exception is being thrown. If we don’t include a throws clause in the method signature, the compilation error “unhandled exception in method” will appear. Refer to this tutorial to learn how the throws clause functions: in Java, throws a keyword.

class InvalidProductException extends Exception
{
    public InvalidProductException(String s)
    {
        // Call constructor of parent Exception
        super(s);
    }
}
 
public class Example1
{
   void productCheck(int weight) throws InvalidProductException{
	if(weight<100){
		throw new InvalidProductException("Product Invalid");
	}
   }
   
    public static void main(String args[])
    {
    	Example1 obj = new Example1();
        try
        {
            obj.productCheck(60);
        }
        catch (InvalidProductException ex)
        {
            System.out.println("Caught the exception");
            System.out.println(ex.getMessage());
        }
    }
}

Output:

Caught the exception
Product Invalid

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button