Site icon TechVidvan

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:

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:

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:

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:

throw keyword Vs. try…catch…finally:

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.

Exit mobile version