• Articles
  • Tutorials
  • Interview Questions

What are Throw and Throws in Java?

Table of content

Show More

Java, originally Oak named and later renamed after the refreshing coffee Java, is the basis of modern programming used by about nine million developers worldwide and runs on more than 95 percent of desktops in businesses. The scale of its adoption shows how adaptable and reliable it can be. For instance, amongst many other things, it has robust facilities for error control using ‘throws’ and ‘throw’ statements that handle run-time exceptions or errors. In this blog post, we shall take a deep look into ‘throw’ and ‘throws’ in Java programming to see how these features make coding easier regarding reliability and maintainability as illustrated through live examples. Get set to become an expert in strong Java programming!

Video Thumbnail

Watch this Java video by Intellipaat:

What is the throw Keyword in Java?

The throw keyword is used to directly throw an exception, which means the programmer can identify an exceptional condition within the program flow, allowing for custom error handling. To handle the exception thrown, the try-catch block is used. The flow of execution of a program switches from the try block to the nearest catch block when an exception is thrown.

In other words, when you expect something to go wrong in your code, you put it inside a try-catch block. If something goes wrong (an exception is thrown), the program jumps to the catch block to deal with it.

Syntax of Java throw 

The syntax for using the throw keyword in Java is as follows:

throw exceptionObject;

Here, “exceptionObject” is an instance of a class that extends the “Throwable class” (base class for all exceptions and errors) either directly or indirectly, such as Exception or Error. This syntax is used to generate and throw an exception during the execution of a program.

Example of Java throw

Let’s understand how the throw keyword is used in a program with the help of a simple example:

public class Test {
    public static long getFactorial(final int num) {
        if (num >= 0 && num < 15) {
            long fact = 1;
            for (int i = 1; i <= num; i++) {
                fact *= I;
            }
            return fact;
        } else {
            // throw new exception here
            throw new IllegalArgumentException("Please provide a valid argument");
        }
    }
    public static void main(String[] args) {
        try {
            System.out.println(getFactorial(6));
            System.out.println(getFactorial(-6));
        } catch (IllegalArgumentException e) {
            System.out.println("Exception caught: " + e.getMessage());
        }
    }
}

Output:

720

Exception caught: Please provide a valid argument

In this Java example, we are calculating the factorial of a positive integer. The method takes an integer ‘num’ as input and returns the factorial of ‘num’. The method checks whether the provided input is within the valid range, and if not, it throws an ‘IllegalArgumentException’ with the message “Please provide a valid argument.” 

What is the throws Keyword in Java?

The “throws” keyword in Java tells you what kinds of problems a method might have while it’s running. It’s like knowing what could go wrong.

The exception is caught in a try-catch block, and an error message is printed. When a method uses the ‘throws’ keyword in its declaration, it’s a way of informing the code that the method might come across an exception while it’s running. 

The throws keyword is used to prevent compile time errors. The throws keyword can be used to assign the caller (which could be a method or a JVM) the task of handling exceptions.

What is the throws Keyword in Java

Syntax of Java throws

The syntax for using the throw keyword in Java is as given below:

returnType methodName(parameters) throws exceptionType1, exceptionType2, ... {

There can be more than one type of exception that a method might throw. These are represented by exceptionType1 and exceptionType2 in the syntax. 

Example of Java throws

Let’s consider a simple example where a method calculates the division of two numbers. It can throw an exception if the divisor is zero, as the result will be infinite. In this case, we’ll use the ‘throws’ keyword to indicate that the method might throw an ‘ArithmeticException’.

public class DivisionCalculator {
    // A method that performs division and throws ArithmeticException if the divisor is zero
    public static double divide(int dividend, int divisor) throws ArithmeticException {
        if (divisor == 0) {
            throw new ArithmeticException("Cannot divide by zero");
        }
        return (double) dividend/divisor;
    }
    public static void main(String[] args) {
        // Using the divide method and handling the potential exception
        try {
            double result = divide(10, 2);
            System.out.println("Result: " + result);
            // Attempting to divide by zero (potential exception)
            result = divide(5, 0); // This line will throw an ArithmeticException
            System.out.println("Result: " + result); // This line won't be reached due to the exception
        } catch (ArithmeticException e) {
            System.err.println("Error: " + e.getMessage());
        }
    }
}

In this example, the ‘divide’ method takes two parameters (dividend and divisor) and performs the division. If the divisor is zero, it throws an ‘ArithmeticException’ with the message “Cannot divide by zero.” 

The output of this program is as follows:

Result: 5.0

Error: Cannot divide by zero

Difference Between throw and throws in Java

The following table summarizes the differences between throw and throws in Java:

Featurethrowthrows
UsageUsed in a method to purposely throw an errorUsed in the method declaration to show there might be problems
Type of exception thrownIt is required for propagating unchecked exceptions (runtime exceptions).It is used to propagate checked exceptions (compile-time exceptions).
PurposeSignals an exceptional situation within the methodDeclares potential exceptions that might be thrown, informing the calling code
SyntaxThe syntax of the throw keyword includes the instance of the exception to be thrown. The instance variable comes after the throw keyword.In the throws keyword syntax, the class names of the exceptions to be thrown are included. The names of the exception classes come after the throws keyword.
LocationInside the method bodyPart of the method signature

This table provides a concise comparison of the key differences between throw and throws in Java.

Conclusion

Knowing how to use ‘throw’ and ‘throws’ is important for handling errors in Java. These keywords help developers build strong applications that can deal with problems gracefully, making the software more reliable and easier to maintain. By using ‘throw’ and ‘throws’ wisely, developers can improve how their Java programs handle errors, making the user experience smoother.

FAQs

What are the differences between throw and throws keywords in Java?

The keyword throw is used to explicitly cast an exception from within the method or code block, which must be a throwable object. The keyword throws is used in method declarations to indicate that the method can raise exceptions identified by its name.

How do you use throw and throws syntax in Java?

A block or method call for throwing could contain”throw new ExceptionType(“errorMessage”);”. In contrast, for throws, returnType methodName(parameters) throws ExceptionType1, ExceptionType2 { }, which means that this type of error can happen during execution.

Can throw and throws in Java both declare unchecked and checked exceptions?

Yes, it is possible to declare both checked and unchecked exceptions using throw and throws, respectively. Checked exceptions require either catching them or declaring them by using the ‘throws’ statement but not unchecked ones.

Define throwable as used in Java.

throwable serves as a superclass for all Error and Exception classes found in Java; it consists of Error (serious problems) as well as Exceptions (problems that programs might want to handle).

Course Schedule

Name Date Details
Python Course 14 Dec 2024(Sat-Sun) Weekend Batch View Details
21 Dec 2024(Sat-Sun) Weekend Batch
28 Dec 2024(Sat-Sun) Weekend Batch

About the Author

Senior Consultant Analytics & Data Science

Sahil Mattoo, a Senior Software Engineer at Eli Lilly and Company, is an accomplished professional with 14 years of experience in languages such as Java, Python, and JavaScript. Sahil has a strong foundation in system architecture, database management, and API integration.