Java Throw Keyword

Exceptions in Java enable us to build high-quality code where faults are verified at compile time rather than run time and where we may define unique exceptions to facilitate code recovery and debugging.

Some of the scenarios have been given below,

Purpose:

When a program is running, the throw keyword is used to consciously raise exceptions to signal extraordinary or incorrect circumstances.

Exception Creation:

To indicate unusual circumstances, throw creates an instance of an exception class and throws it.

Custom Exceptions:

By extending existing exception types, developers can construct their own unique exception classes that are tailored to the demands of particular applications.

Syntax:

The syntax for using throw is:

throw exceptionObject;,

Where exceptionObject is an instance of an exception class.

Exception Handling:

Thrown exceptions are caught and managed using try, catch, and finally, blocks, facilitating structured error handling.

Predefined Exceptions:

Each class in Java’s hierarchy of predefined exceptions represents a distinct kind of error or extraordinary circumstance.

Error Messages:

Developers can attach illustrative error messages with their exception throws to explain the reason for the uncommon circumstance.

Controlled Flow:

When exceptional circumstances arise, the throw keyword enables more controlled program flow.

Robustness:

By enabling methodical management of runtime problems, proper throw usage facilitates the construction of robust programming.

Example:

Throwing Unchecked Exception

Example code:

class DivisionExample {
        public static void main(String[] args) {
            int dividend = 10;
            int divisor = 0;
            try {
                int result = divide(dividend, divisor);
                System.out.println("Result of division: " + result);
            } catch (ArithmeticException ex) {
                System.out.println("Caught an arithmetic exception: " + ex.getMessage());
            }
        }
        public static int divide(int dividend, int divisor) {
            if (divisor == 0) {
                throw new ArithmeticException("Division by zero is not allowed.");
            }
            return dividend / divisor;
        }
}

Output:

Caught an arithmetic exception: Division by zero is not allowed.

Explanation:

  • In this example, we have a divide method that takes two integers as arguments and attempts to perform division. However, before performing the division, the method checks if the divisor is zero. If it is, the method throws an instance of the ArithmeticException class, which is an unchecked exception.
  • In the main method, we call the divide method with a divisor of zero, intentionally triggering the ArithmeticException. We catch the exception using a try-catch block and print an error message.
  • The unchecked exception ArithmeticException is commonly thrown when an arithmetic operation encounters an exceptional condition, such as division by zero in this case.

1. Program:

class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}
public class ThrowExample {
    static void validateAge(int age) throws CustomException {
        if (age < 18) {
            throw new CustomException("Person is not of legal age");
        } else {
            System.out.println("Person is eligible");
        }
    }
   public static void main(String[] args) {
        try {
            int personAge = 15;
            validateAge(personAge);
        } catch (CustomException e) {
            System.out.println("Caught exception: " + e.getMessage());
        }
    }
}

Output:

Caught exception: Person is not of legal age

Explanation:

  • The code defines a custom exception class CustomException that extends the built-in Exception class.
  • The validateAge method takes an int parameter age and throws a CustomException if the age is less than 18. If the age is 18 or older, it prints “Person is eligible”.
  • In the main method, an int variable personAge is assigned a value of 15.
  • The validateAge method is called with personAge as the argument. Since personAge is less than 18, the throw statement in the validateAge method is executed, throwing a CustomException.
  • The thrown exception is caught by the catch block that specifies CustomException as the type of exception to catch. The caught exception is referred to as e.
  • Inside the catch block, the error message of the caught exception (e.getMessage()) is retrieved and printed.

2. Program

class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}
public class StudentAgeValidator {
    static void validateAge(int age) throws CustomException {
        if (age < 0) {
            throw new CustomException("Age cannot be negative");
        } else if (age < 18) {
            throw new CustomException("Student is underage");
        } else {
            System.out.println("Student age is valid");
        }
    }
    public static void main(String[] args) {
        try {
            int studentAge = -5;
            validateAge(studentAge);
        } catch (CustomException e) {
            System.out.println("Caught exception: " + e.getMessage());
        }
    }
}

Output:

Caught exception: Age cannot be negative

Explanation:

  • The CustomException class is defined, which extends the built-in Exception class. It has a constructor to set the exception message.
  • The StudentAgeValidator class contains a validateAge method that checks the validity of a student’s age. It throws the custom CustomException based on different conditions.
  • In the main method, an int variable studentAge is assigned a value of -5.
  • The validateAge method is called with studentAge as an argument. Since studentAge is negative, the first condition in the validateAge method is satisfied, leading to the throw statement being executed. This throws a CustomException with the message “Age cannot be negative”.
  • The thrown exception is caught by the catch block that specifies CustomException as the type of exception to catch. The caught exception is referred to as e.
  • Inside the catch block, the error message of the caught exception (e.getMessage()) is retrieved and printed.

Summary

The throw keyword in Java is a powerful tool for managing exceptions and error handling. It enables developers to intentionally trigger exceptions, creating a controlled way to respond to unexpected situations and ensure the reliability of their programs.

Difference between throw and throws:

Aspect throw throws
  

 Usage

Used inside a method to manually throw an exception. Used in method declarations to specify potential exceptions that might be thrown by the method.
 

 Syntax

throw exceptionInstance; returnType methodName(parameters) throws ExceptionType1, ExceptionType2, …;
 What It Does Signals are an exceptional condition within the method. Declares the exceptions that the method might propagate to its caller.
 Handling Requires the caller to catch or propagate the thrown exception. Informs the caller about the exceptions that need to be handled when calling the method.
 Exception Type Followed by an instance of an exception class or a subclass of Throwable. Followed by a comma-separated list of exception classes.
 Checked/Unchecked It can be used to throw both checked and unchecked exceptions. Declares both checked and unchecked exceptions that might be thrown.
 In Method Body Used inside a method’s body to explicitly throw an exception. Not used within the method body; only in the method’s declaration.
 Mandatory It is not mandatory; it is used when the programmer wants to throw an exception. Not mandatory; used to indicate the potential exceptions the method might throw.

Throwing multiple exceptions in Java:

public class MultipleExceptionsExample {
    public static void main(String[] args) {
        try {
            processInput(-10);
        } catch (IllegalArgumentException ex) {
            System.out.println("Caught IllegalArgumentException: " + ex.getMessage());
        } catch (ArithmeticException ex) {
            System.out.println("Caught ArithmeticException: " + ex.getMessage());
        }
    }

    public static void processInput(int value) throws IllegalArgumentException, ArithmeticException {
        if (value < 0) {
            throw new IllegalArgumentException("Input value cannot be negative.");
        }
        if (value == 0) {
            throw new ArithmeticException("Input value cannot be zero.");
        }
        System.out.println("Input value is valid.");
    }
}

Output:

Caught IllegalArgumentException: Input value cannot be negative.

Explanation:

  • In this example, the processInput method can throw both IllegalArgumentException and ArithmeticException. These exceptions are declared using the throws clause in the method signature.
  • In the main method, we call the processInput method with different input values. If the input value is negative, an IllegalArgumentException is thrown, and if the input value is zero, an ArithmeticException is thrown. We use separate catch blocks to handle each type of exception and print appropriate messages.
  • Remember that when you declare multiple exceptions in the throws clause, they are typically comma-separated. When calling the method that can throw these exceptions, you need to either handle them using separate catch blocks or declare that your calling method can also throw these exceptions using its own throws clause.

throw keyword Vs. try…catch…finally:

  • the throw keyword is used to manually throw exceptions
  • try…catch…finally is used to handle exceptions within a specific code block, allowing for graceful recovery and cleanup tasks.

Conclusion

In the grand symphony of Java programming, the throw keyword is a pivotal note that resonates when disorder threatens the harmonious code. It hands developers the baton to conduct precise exception scenarios, sculpting graceful error handling and preserving the stability of applications. By grasping the significance and artistry of the throw keyword, Java programmers unlock a realm of controlled chaos that elevates software from mere functionality to true reliability.