Throws and Throw in Java Explained

Throws and Throw in Java Explained

Exception Handling in Java

In Java, there is a powerful mechanism for handling run-time errors. This mechanism is known as Exception handling. Exception handling is used to maintain the normal flow of the application.

Types of Java Exceptions

Mainly two types of exceptions are defined in java namely: checked and unchecked. An error that occurred in java is considered an unchecked exception. But three types of exceptions are defined by the Oracle. These exceptions are given below:

  1. Checked Exception

  2. Unchecked Exception

  3. Error

Checked Exception

Checked Exceptions are those exceptions that inherit the Throwable class directly except Error and RunTimeException.

Checking of checked exceptions is at compile-time. IOException and SQL exceptions are some examples of checked exceptions.

Unchecked Exception

Unchecked exceptions in java are those exceptions by which runtimeExceptions are inherited. ArrayIndexOutOfBoundsException, NullPointerException, ArithmeticException and so on are some examples of unchecked exceptions. These are checked at runtime instead of compile-time.

Error

Error is considered irrecoverable. AssertionError, OutOfMemoryError, VirtualMachineError and so on are some examples of errors that occurred in java.

Java Exception Keywords

5 keywords are given by java for handling the exceptions. All five keywords are described below:

try

The "try" keyword is used for defining the block where we should place the code in which an exception may occur. Try keywords are not allowed to be used alone. We need to use either catch or finally keyword while using the try block.

catch

The "catch" keyword is used to handle the exception. Just like try block, catch block is not allowed to be used alone. So, a try block must be used before implementing the catch block. After the implementation of the catch keyword finally block can also be used.

finally

Whenever there is a need to execute the necessary code of the program, we use the "finally" block. Its main purpose is to execute the code irrespective of whether an exception is handled or not.

throw

When there is a need to throw an exception. Then, the "throw" keyword is used for this purpose.

throws

The "throws" keyword is used to declare an exception. It is used for identifying what may be an exception in the method. Throwing an exception is not allowed in this keyword. throws keyword must be used with the Method signature.

throw and throws in java

The throw and throws both keywords are used for exception handling where for throwing the exception from a block of code or method explicitly throw keyword is used on the other hand throws keyword is used with the method signature for representing that there is a chance of occurrence of exception in the method.

Throw and throws keywords are different from each other in various aspects. The difference given below describes how throw and throws keywords are different from each other.

Sr. no.

Basis of Differences

throw

throws

1.

Definition

The throw keyword is used to throw the exception explicitly in the program code, block of the code or inside the function.

Java throws keyword is used in the method signature to declare an exception which might be thrown by the function while the execution of the code.

2.

Type of exception 


Throw keyword only allow unchecked exceptions to be propagated. It does not allow checked exceptions to be propagated.


Both Checked and unchecked exceptions are allowed to be declared with the help of the throws keyword. Only checked exceptions are propagated by this keyword also.

3.

Syntax

The throw keyword is written followed by the thrown exception instance.

The throws keyword is used by following the method signature and followed by the name of the Exception classes which the method can throw.

4.

Declaration


We use the throw keyword within the method.


This keyword is used with the signature of the method

5.

Internal implementation


Throw keywords allow only one exception to be thrown at the time. Multiple exceptions are not allowed to be thrown at a same time

The throws keyword allows multiple exceptions to be declared that the method can throw. Such as main() throws IOException and SQLException.

Java throw Example

Below is an example to demonstrate the use of the throw keyword. In the below lines of code, the throw keyword is used to throw an exception explicitly when the age is negative. A method is defined to check the age it will throw an exception if the age is negative otherwise it will display the age simply.

ThrowExample.java

// defining the class
public class ThrowExample {
    // declaring the method for checking the age 
    public static void checkAndPrintAge(int age) {
        // checking if age is negative then simply throw an exception
        if (age < 0) {
            throw new ArithmeticException("Sorry!! Value of age can not be negative");
        } else {
            System.out.println("Your age is " + age);
        }
    }
    //main method  
    public static void main(String[] args) {
        // creating an object
        ThrowExample obj1 = new ThrowExample();
        // calling method checkAndPrintAge method for positive age value
        obj1.checkAndPrintAge(9);


        // calling method checkAndPrintAge method for negative age value
        obj1.checkAndPrintAge(-3);
        // rest of code to be executed
        System.out.println("Rest of the code..");
    }
}

Output:

Your age is 9
Exception in thread "main" java.lang.ArithmeticException: Sorry!! Value of age can not be negative
        at ThrowExample.checkAndPrintAge(Main.java:7)
        at ThrowExample.main(Main.java:20)

Java throws Example

Below is an example to demonstrate the use of the throws keyword. In the below lines of code, a keyword is used to declare an exception class that can occur inside the method and inside the main method at the time of the calling of this method we will handle the exception.

ThrowsExample.java

// defining the class
public class ThrowsExample {
    // declaring the method for dividing two numbers and declaring ArithmeticException using throws keyword


    public static int numbersDivision(int val1, int val2) throws ArithmeticException {
        // calculating division value
        int division = val1 / val2;
        // returning the division value
        return division;
    }
    //main method  
    public static void main(String[] args) {
        // creating an object
        ThrowsExample obj1 = new ThrowsExample();
        // calling method inside the try block
        try {
            System.out.println(obj1.numbersDivision(45, 0));
        }
        // handling the exception thrown by the method using catch block
        catch (ArithmeticException e) {
            System.out.println("Division cann’t possible, as number can not be divided by the zero");
        }
        // rest of code to be executed
        System.out.println("Rest of the code..");
    }
}

Output:

Division cann’t possible, as number can not be divided by the zero
Rest of the code..

Java throw and throws Example

Below is an example to demonstrate the use of the throw and throws keywords both. TestThrowAndThrows.java

// defining the class
public class ThrowAndThrowsExample {
    // declaring the method by which exception can be thrown
    static void testMethod() throws ArithmeticException {
        System.out.println("In the method testMethod()");
        // explicitly throwing an exception using throw keyword  
        throw new ArithmeticException("throwing an ArithmeticException");
    }
    //main method  
    public static void main(String args[]) {
        // creating an object
        ThrowAndThrowsExample obj1 = new ThrowAndThrowsExample();
        // calling testMethod method inside the try block
        try {
            obj1.testMethod();
        }
        // handling exception using the catch block
        catch (ArithmeticException e) {
            System.out.println("exception caught in the main() method");
        }
        // rest of code to be executed
        System.out.println("Rest of the code..");


    }
}

Output:

In the method testMethod()
exception caught in the main() method
Rest of the code..