In this post we will learn how to throw an exception in java, to do so, we will cover the following topics:
- What is throw in Java?
- How to throw an Exception in Java
- Examples
So, let’s begin!
What is throw in Java?
It is a keyword that is used to throw an explicit exception. We can specify the user-defined exception object and throw it explicitly using the throw keyword.
How to throw an Exception in Java
In this section, we will consider a couple of examples to learn how to throw an exception in java.
Example1
In this example we will create a user-defined method named verify(int num) that will take a numeric parameter. If the passed value is greater than 26, then the verify() method will throw an arithmetic exception, else if the passed value is less than or equal to 26 then the verify() method will show a greeting message.
public static void verify(int num) {
if(num > 26) {
throw new ArithmeticException("Over Aged! not eligible for this job");
}
else {
System.out.println("Congratulations! you are eligible for this job");
}
}
public static void main(String[] args){
verify(29);
}
}
The above program will produce the following output:
Above snippet verifies the working of the throw keyword.
Example2
We can define our own set of rules, and based on these rules we can throw an exception using throw keyword. In this example, we will throw an ArithmeticException if the divide() method receives a number zero:
public static void divide(int num) {
if(num == 0) {
throw new ArithmeticException("Error: Enter other than zero");
}
else {
num = 150%num;
System.out.println("Remainder: " + num);
}
}
public static void main(String[] args){
divide(0);
}
}
In the above program, the divide method received a value “0” so it will throw the Arithmetic Exception along with the user-specified message:
In this way, we can throw a custom exception in java.
Conclusion
In java, the throw is a keyword that is used to throw an explicit exception. We can specify the user-defined exception object and throw it explicitly using the throw keyword. We can define our own set of rules, and based on these rules we can throw the exception using the throw keyword. This write-up explains how to throw an exception in java using the throw keyword. Moreover, it presents a couple of examples for a profound understanding of the throw keyword.