top

Search

Java Tutorial

.

UpGrad

Java Tutorial

Difference Between Throw and Throws in Java

Introduction

Error handling is a key concept every programmer should master before creating deployable applications. No matter how sophisticated the code is, every program will throw errors during compilation or runtime.

It is prudent to know how to handle these errors, and the most common way to handle them is by handling the exceptions that the code might raise. Exception handling doesn’t only pertain to Java but almost every programming language that exists.

In this read, we’re going to delve into the difference between throw and throws in Java, we’re going to look into the code for both and how to implement both of these keywords into programs. Read on to learn how to implement the throw and throws clause in your code.

Overview

The throw and throws keyword in Java is used to handle exceptions you know your code might raise. For example, if you create a program that takes a number from the user and then divides it by another number given by the user, there is a chance that the user might enter ‘0’ as the divisor.

If you do not have this exception handled, your program will throw an error and not provide you with the desired output. So you can handle the exception by providing a customized message saying, “The divisor cannot be zero”.

The above is a small example of how exceptions are handled using the throw clause. However, in production-ready applications, exception handling is used extensively.

Key Difference Between Throw and Throws

There are a few key differences between throw and throws in Java mentioned in the table below:

Throw

Throws

The "throw" exception in Java is used within the body of a method to throw an exception explicitly.

The "throws" keyword is used in the method signature to declare the potential exceptions that a method may throw.

It allows programmers to create their own exceptions or throw predefined exceptions to handle specific scenarios.

It informs the caller of the method and possible exceptions that need to be handled or propagated.

It is used when a specific condition or error occurs within the method that requires an exception to be thrown.

It does not throw exceptions; it is a declaration mechanism.

It transfers the control to the caller, indicating an exceptional condition.

It allows the caller to handle the declared exceptions or pass them on to higher-level methods.

Java Throw Example

As we now know the key differences, let’s delve into the coding segment to understand the difference between throw and throws with example in Java. We’ll get into the throw clause and how to handle exceptions using Java:

Arithmetic Exception using throw clause:

public class Throw {
    public static void main(String[] args) {
        try {
            int result = divide(10, 0);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
    public static int divide(int dividend, int divisor) {
        if (divisor == 0) {
            throw new ArithmeticException("Cannot divide by zero");
        }
        return dividend / divisor;
    }
}

In the example above, we have a function called ‘divide’ that takes two integers in as arguments and performs division.

The parameters passed while invoking the function ‘divide’, are ‘10’ and ‘0’, ‘0’ being the divisor. The function throws an ArithmeticException with a custom error message saying that the dividend cannot be divided by the divisor ‘0’.

In the main method, we’re invoking the divide method within a try-catch block to handle the exception. If an exception is thrown in the try block, the catch block is executed, and the error message is printed.

e.getMessage() is a method that is used to retrieve the error message associated with an exception object e. You can rename ‘e’ to what you desire, but you have to change it according to the occurrences of the code.

The getMessage() method is an in-built method provided by Java that lets you access the error message as a string.

Do-it-yourself

Try changing the value of the divisor to ‘1’ in the ‘try’ block in the above program to see the results.

Replace int result = divide(10, 0); with int result = divide(10, 1);

Below are a few more examples of how you can use the ‘throw’ clause for more exceptions:

NullPointerException

public class Throw{
    public static void main(String[] args) {
        try {
            String text = null;
            if (text == null) {
                throw new NullPointerException("Text is null");
            }
        } catch (NullPointerException e) {
            System.out.println("NullPointerException occurred: " + e.getMessage());
        }
    }
}

To handle the NullPointerException using the “throw” clause, we’re declaring a String called “text” and set its value to null inside the try block. Note that we’re explicitly trying to create the NullPointerException in the code above.

We use a conditional statement after that to check whether the String “text” value is null or not. If it is null, then we “throw” a NullPointerException saying that the “Text is null”, catch the same exception in the catch block, and display a custom message addressing the NullPointerException.

ArrayIndexOutOfBoundsException

public class Throw{
    public static void main(String[] args) {
        try {
            int[] numbers = {1, 2, 3};
            int index = 3;
            if (index < 0 || index >= numbers.length) {
                throw new ArrayIndexOutOfBoundsException("Invalid index: " + index);
            }
            int value = numbers[index];
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("ArrayIndexOutOfBoundsException occurred: " + e.getMessage());
        }
    }
}

In the code above, we’re explicitly trying to raise the ArrayIndexOutOfBoundsException. When you try to access an array backed with a non-existent index, you get an ArrayIndexOutOfBoundsException. This exception signifies that the index you’re trying to access is either less than 0 or more than or equal to the array's length.

In the ‘try’ block, we take an array of the integer data type called ‘numbers’ and add the elements 12, and 3 in it. So the accessible indexes are 01, and 2. Next, we take an integer called index and assign the value of 3 to it.

We use the “if” statement to check whether the index is less than ‘0’ or greater than the length of the array, i.e., 3. In case the “if” statement returns a “TRUE” value, we use the “throw” clause to raise an ArrayIndexOutOfBoundsException, handle it in the catch block, and print a customized message.

Java Throws Example

The "throws" keyword is used in the method signature to declare the potential exceptions that a method may throw. Keep reading if you’re wondering in which situation the throws clause is used.

Let’s take the same example of an ArithmeticException used in the example above and implement the same using the “throws” keyword.

public class Throws {
    public static void main(String[] args) {
        Throws calculate = new Throws();
        int dividend = 10;
        int divisor = 0;
        try {
            int result = calculate.divide(dividend, divisor);
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
    public int divide(int dividend, int divisor) throws ArithmeticException {
        if (divisor == 0) {
            throw new ArithmeticException("Division by zero is not allowed.");
        }
        return dividend / divisor;
    }
}

In the example above, we declare the divide method to throw an ArithmeticException using the “throws” keyword. Any code calling this method must handle or declare this exception.

We check if the divisor is ”0” within the method divide. If it is “0”, we throw a new ArithmeticException with a specific error message using the throw keyword.

In the main method, we create an instance of the class “Throws” and call the divide method. We put the function ‘divide’ on the object ‘calculate’ in a try-catch block to catch any ArithmeticException that may be thrown. If the exception occurs, i.e., when the divisor is ‘0’, we print an error message.

Using the ‘throws’ keyword, we inform callers that the divide method may throw an ArithmeticException if an invalid division operation occurs.

The advantage of using “throws ArithmeticException” is that anyone trying to use the function “divide” will have to handle or declare the exception in their main() method. This makes the function reusable within any class and reduces the chances of errors. 

Conclusion

Exception handling is a key concept to learn if you are trying to code in Java. Instead of letting the program throw you unexpected errors, it is much wiser to put your code in the try-, catch- and finally-block in Java and handle those errors using the throw and throws clause.

Developers use both clauses in their code extensively as it helps them deal with potential problems that might arise during the runtime of their application. It also helps with the entire debugging and troubleshooting process, providing a mechanism to locate and diagnose the problems within their code.

FAQs

1. What is the finally keyword in Java?

The finally keyword in Java is used to run a segment of code under the ‘finally’ block. This code segment will execute regardless of whether an exception occurs.

2. Is there a difference between throw and throws in C#?

The ‘throws’ clause does not exist in C#. Exceptions in C# are handled using the ‘throw’ keyword.

3. What is throwable in Java?

"Throwable" refers to a class hierarchy representing exceptions and errors. All exceptions and errors commence in the Throwable class.

Leave a Reply

Your email address will not be published. Required fields are marked *