Throwing Exceptions
In Java, you can throw exceptions using the throw
keyword. This tutorial will teach you how to create and throw your own exceptions.
Using the Throw Keyword
To throw an exception, use the throw
keyword followed by an instance of the exception class:
public class Main {
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 at least 18");
} else {
System.out.println("Access granted");
}
}
}
In this example, the checkAge
method throws an exception if the age is less than 18.
Custom Exceptions
You can create your own custom exceptions by extending the Exception
class:
class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
}
public class Main {
public static void main(String[] args) {
try {
validate(10);
} catch (CustomException e) {
System.out.println("Caught the exception");
System.out.println(e.getMessage());
}
}
static void validate(int number) throws CustomException {
if (number < 20) {
throw new CustomException("Number is less than 20");
}
}
}
In this example, the CustomException
class is a custom exception that is thrown when the number is less than 20.
Continue exploring our intermediate tutorials to learn more about Java programming.