In the post, we learn another new concept of exception handling: how to create a custom exception and handle such types of exceptions using Throw and Throws.
Why Throw and Throws in Java?
As we know, in Java programming language, some predefined exception classes are present, like ArithmeticException, NullPointerException, ArrayIndexOutOfBounds exception, etc. These exceptions are triggered according to the different conditions; if you try to divide a number by zero, your ArithmeticException will trigger.
Apart from the predefined exception, we can define our exception with some set of rules and conditions, and we can also throw such type of exception by using the throw keyword. With the help of the throw keyword, we can throw Predefined exceptions and custom exceptions.
Throw Keyword Syntax
throw new exception_class("error message");
Throw Keyword example
/* In this program we are checking the Student age * if the student age<12 and weight <40 then our program * should return that the student is not eligible for registration. */ public class ThrowExample { static void checkEligibilty(int stuage, int stuweight) { if(stuage<12 && stuweight<40) { throw new ArithmeticException(“Student is not eligible for registration”); } else { System.out.println(“Student Entry is Valid!!”); } } public static void main(String args[]) { System.out.println(“Welcome to the Registration process!!”); checkEligibilty(10, 39); System.out.println(“Have a nice day..”); } }
User-defined or Custom exception in Java
Using the Java programming language, we can create our custom exception class and throw that exception using the Java keyword throw. Such types of exceptions are called custom or user-defined exceptions.
In this core Java exception tutorial series, we will learn how to create and throw our custom exception in a particular condition.
Note:
- The user-defined exception class must extend the Exception class
- The exception we throw using the throw keyword.
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 a 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) ; } } }
Throws in Java
In our previous post, we discussed checked and unchecked exceptions, where we mentioned that if there is a checked exception, you have to handle that; otherwise, the program will not compile.
Similarly, the unchecked exception is not checked during the compile-time, and for the handle, the unchecked exception throws keyword is used. This throws keyword is used in the signature of the methods to indicate that the method might throw any of the listed types of exceptions. The caller method has to handle the exception using the try-catch block; otherwise, you will get a compile-time error.
public void myMethod() throws ArithmeticException, NullPointerException { // Statements that might throw an exception } public static void main(String args[]) { try { myMethod(); } catch (ArithmeticException e) { // Exception handling statements } catch (NullPointerException e) { // Exception handling statements } }
Example of throws Keyword
import java.io.*; class ThrowExample { void myMethod(int num)throws IOException, ClassNotFoundException { if(num==1) throw new IOException("IOException Occurred"); else throw new ClassNotFoundException("ClassNotFoundException"); } } public class Example1 { public static void main(String args[]) { try { ThrowExample obj=new ThrowExample(); obj.myMethod(1); }catch(Exception ex) { System.out.println(ex); } } }
Here, we will see a few examples of throws keyword. To understand these programs, you should know the throws keyword in Java.
Example 1: Exception propagation using throws keyword
As you can see, an exception occurred in method1, which has been handled in the chain-calling method method3(). This example shows how the exception propagation works.
class Example1 { void method1() throws ArithmeticException { throw new ArithmeticException("Calculation error"); } void method2() throws ArithmeticException { method1(); } void method3() { try{ method2(); } catch(ArithmeticException e) { System.out.println("ArithmeticException handled"); } } public static void main(String args[]) { Example1 obj=new Example1(); obj.method3(); System.out.println("End Of Program"); } }
Output:
ArithmeticException handled End Of Program
Example 2: When you don’t handle the exception and instead declare it at all the places
The ideal way to use throws is by declaring the exceptions in the method signature and handling the exceptions using try-catch in the calling method. Let us see what happens when we declare the exception at both places, in the method signature and in the calling method.
class ExceptionExample { void method()throws ArithmeticException { throw new ArithmeticException("ArithmeticException Occurred"); } } class Example1 { public static void main(String args[])throws ArithmeticException { ExceptionExample obj=new ExceptionExample(); obj.method(); System.out.println("End Of Program"); } }
How do you handle Exceptions Manually using throw keywords in Java?
package com.softwaretestingblog.programs; public class HandleExceptionManually { public static void main(String[] args) { // TODO Auto-generated method stub try { int i=9; @SuppressWarnings("unused") int z=i/0; //throw new Exception(); throw new ArithmeticException(); } catch(ArithmeticException e)//Subclass Always in Top { System.out.println(e.getMessage()); System.out.println("Arithmatic Exception "); } catch(Exception e) // Super Class Always Down { System.out.println(e.getMessage()); System.out.println("Arithmatic Exception "); } } }
Output:
/ by zero Arithmatic Exception