Last chance! 50% off DataCamp Premium
Sale ends in
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.
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.
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.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.
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.
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.
throw new IllegalArgumentException("Parameter 'x' cannot be negative.");
@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.");
}
}