User Defined Exceptions (Java)



What is User Defined Exception in Java?

User Defined Exception or custom exception is creating your own exception class and throws that exception using ‘throw’ keyword. This can be done by extending the class Exception.
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.

Example of User defined exception in Java:

import java.io.IOException;
import java.util.Scanner;

public class InternalMarks extends Exception {
public InternalMarks(String s) {
super(s);
}
}
public class ExternalMarks extends Exception {
public ExternalMarks(String s) {
super(s);
}
}

public class Main {

public static void main(String args[]) throws IOException
{
int x,y;
Scanner s = new Scanner(System.in);
System.out.println("Enter Internal Marks");
x=s.nextInt();
if(x>40)
{
try {
throw new InternalMarks("Internal Marks > 40");
} catch (InternalMarks e) {
// TODO Auto-generated catch block
e.printStackTrace();

}
else
{
System.out.println("Internal MARKS = "+ x);
}
System.out.println("Enter External Marks");
y=s.nextInt();
if(y>60)
{
try {
throw new InternalMarks("External Marks Exceeded");
} catch (InternalMarks e) {
// TODO Auto-generated catch block
e.printStackTrace();

}
else
{
System.out.println("External MARKS = "+ y);
}

}
}

Recommended: solve it on “PRACTICE ” first, before moving on to the solution.


Run:

https://onlinegdb.com/B1v8lUgmU
Previous Post Next Post