Computer Science, asked by pandey7579, 1 year ago

What is user defined exception in Java?

Answers

Answered by kerthi111
0
In java we have already defined, exception classes such as ArithmeticException, NullPointerException etc. These exceptions are already set to trigger on pre-defined conditions such as when you divide a number by zero it triggers ArithmeticException, In the last tutorial we learnt how to throw these exceptions explicitly based on your conditions using throw keyword.

In java we can create our own exception class and throw that exception using throw keyword. These exceptions are known as user-defined or custom exceptions. In this tutorial we will see how to create your own custom exception and throw it on a particular condition.

To understand this tutorial you should have the basic knowledge of try-catch block and throw in java.

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) ; } } }
Answered by ridhimasharma8
0

User defined exception or custom exception is creating you own exception class and throws using'throw' keyword. the keyword 'throw' is used to creat a new exception and throw it to the catch block.


maddy0507: heyyy
maddy0507: nyc answer
maddy0507: thanks
Similar questions