Java throw
Created By: chatGPT
Throwing exceptions in Java is a way to signal that an error or unexpected condition has occurred. When you want to indicate that something went wrong during the execution of your program, you can use the
In the code above, the throw
statement to explicitly throw an exception. This allows you to control the flow of your program and handle errors gracefully. Below is a simple example demonstrating how to throw an exception: public class Example {
public static void main(String[] args) {
try {
checkAge(15);
} catch (IllegalArgumentException e) {
System.out.println(e.getMessage());
}
}
public static void checkAge(int age) {
if (age < 18) {
throw new IllegalArgumentException("Age must be at least 18.");
}
System.out.println("Access granted.");
}
}
checkAge
method checks if the provided age is less than 18. If it is, we use the throw
statement to throw an IllegalArgumentException
. The error message helps to indicate the reason for the exception. This exception is then caught in the try-catch block in the main
method, allowing us to handle the error without crashing the program.You can throw either checked or unchecked exceptions. Checked exceptions must be either caught or declared in the method signature, while unchecked exceptions do not have this requirement. Here’s a brief example of each:
In this example, public class CheckedUncheckedExample {
public static void main(String[] args) {
try {
methodThatThrowsCheckedException();
} catch (InterruptedException e) {
System.out.println("Caught a checked exception: " + e.getMessage());
}
// Unchecked exception
methodThatThrowsUncheckedException();
}
public static void methodThatThrowsCheckedException() throws InterruptedException {
throw new InterruptedException("This is a checked exception.");
}
public static void methodThatThrowsUncheckedException() {
throw new RuntimeException("This is an unchecked exception.");
}
}
methodThatThrowsCheckedException
throws a checked exception, requiring it to be caught or declared. On the other hand, methodThatThrowsUncheckedException
throws a runtime exception, which does not require explicit handling. Proper exception handling is crucial for writing robust Java applications.