throw Keyword in Java
The throw
keyword in Java is used to explicitly throw an exception from a method or any block of code. It is an essential part of Java's exception handling mechanism, allowing developers to create and manage error conditions in a controlled manner.
Usage
The throw
keyword is typically used to throw either checked or unchecked exceptions. When an exception is thrown, the normal flow of the program is disrupted, and control is transferred to the nearest enclosing try
-catch
block that can handle the exception.
Syntax
throw new ExceptionType("Error message");
ExceptionType
: The type of exception to be thrown (e.g.,ArithmeticException
,NullPointerException
)."Error message"
: A string message providing details about the exception.
Examples
Example 1: Throwing a Checked Exception
public class ThrowExample {
public static void main(String[] args) {
try {
checkAge(15);
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
static void checkAge(int age) throws Exception {
if (age < 18) {
throw new Exception("Age must be 18 or older.");
}
}
}
In this example, the checkAge
method throws an Exception
if the provided age is less than 18. The main
method calls checkAge
within a try
block and catches the exception, printing the error message.
Example 2: Throwing an Unchecked Exception
public class ThrowExample {
public static void main(String[] args) {
try {
divide(10, 0);
} catch (ArithmeticException e) {
System.out.println(e.getMessage());
}
}
static void divide(int a, int b) {
if (b == 0) {
throw new ArithmeticException("Division by zero is not allowed.");
}
System.out.println(a / b);
}
}
Here, the divide
method throws an ArithmeticException
if the divisor is zero. The main
method catches the exception and prints the error message.
Example 3: Custom Exception
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class ThrowExample {
public static void main(String[] args) {
try {
validate(0);
} catch (CustomException e) {
System.out.println(e.getMessage());
}
}
static void validate(int number) throws CustomException {
if (number <= 0) {
throw new CustomException("Number must be greater than zero.");
}
}
}
This example demonstrates how to throw a custom exception. The validate
method throws a CustomException
if the number is less than or equal to zero, and the main
method catches and handles it.
Tips and Best Practices
- Use Meaningful Messages: Always provide meaningful and descriptive messages when throwing exceptions to make debugging easier.
throw new IllegalArgumentException("Parameter 'x' cannot be negative.");
- Checked vs. Unchecked Exceptions: Use checked exceptions for recoverable conditions and unchecked exceptions (runtime exceptions) for programming errors.
- Custom Exceptions: Create custom exceptions to represent specific error conditions in your application. This makes your code more readable and maintainable.
- Avoid Overuse: Do not overuse exceptions for control flow. They should be used for exceptional conditions, not for regular conditional checks.
- Document Exceptions: Always document the exceptions that a method can throw using the
@throws
Javadoc tag./** * @throws IllegalArgumentException if the parameter is invalid */ public void someMethod(int param) { if (param < 0) { throw new IllegalArgumentException("Parameter cannot be negative."); } }