throw keyword in Java with examples

throw keyword:

The throw keyword is used to explicitly throw an exception during the execution of a Java program. When you encounter an exceptional situation that your code cannot handle, you can use the throw keyword to raise an exception, indicating that something unexpected or erroneous has happened. By throwing an exception, you can transfer the control to the nearest suitable catch block that can handle the exception or propagate it up the call stack to be handled by a higher-level catch block.

throw keyword syntax:

 throw exception;
There are two types of throw exception :
1) throw custom exception class
2) throw inbuild exception 

throw custom exception class: In addition to using built-in exception classes like IllegalArgumentException, you can create your own custom exception classes by extending the Exception or RuntimeException class. Custom exception classes are helpful for representing specific error conditions that are unique to your application or domain.

throw custom exception class example: 
public class CustomExceptionExample {
    public static void main(String[] args) {
        try {
            throw new CustomException("This is a custom exception");
        } catch (CustomException e) {
            System.out.println("Caught custom exception: " + e.getMessage());
        }
    }
}

// Custom exception class
class CustomException extends Exception {
    public CustomException(String message) {
        super(message);
    }
}
Throw built-in exceptions: You can use the throw keyword with built-in exceptions like NullPointerException, ArrayIndexOutOfBoundsException, ArithmeticException, etc. These exceptions provide specific information about the nature of the problem.

throw built-in exception example:
public class BuiltInExceptionExample {
    public static void main(String[] args) {
        String name = null;
        if (name == null) {
            throw new NullPointerException("Name cannot be null");
        }
    }
}

Next Post Previous Post
No Comment
Add Comment
comment url