[!NOTE] Sometimes, an operation is mathematically "successful", but logically invalid for your business logic.
For example, a user trying to withdraw $10,000 when they only have $5 in their bank account. The mathematical subtraction of
5
- 10000
will successfully result in -9995.
This is a business rule failure, not a Java compiler failure. We can force Java to treat this as a fatal error using the throw keyword.
The 'throw' Keyword (Manual Instigation)
The throw statement allows you to create a custom error instantly. By convention, you use this in conjunction with an if statement validating input parameters.
public class SecurityApp { static void checkAge(int age) { if (age < 18) { // 1. Manually instantiate a new Error object and throw it at the JVM! throw new ArithmeticException("Access denied
You must be at least 18 years old."); } else {System.out.println("Access granted
You are old enough!"); }}
public static void main(String[] args) { checkAge(15); // This will crash the app with our custom error message!}}
The 'throws' Keyword (Passing Responsibility)
Sometimes, you don't want to handle an exception inside a small utility method. If a readFile() method fails because the file is missing, it shouldn't be the utility method's job to decide what to show the user.
Using the throws keyword in a method signature warns anyone calling the method: "Hey, this method might explode with an error. I'm not going to catch it. If you call me, YOU must put me in a try-catch block."
import java.io.*;
public class Logger {
// 1. We declare that this method throws an exception.
// We do NOT use try-catch inside this method body.
public static void readSecureFile() throws FileNotFoundException {
File myObj = new File("non_existent_passwords.txt");
Scanner myReader = new Scanner(myObj); // Java knows this could fail
}
public static void main(String[] args) {
// 2. Because readSecureFile() is marked with 'throws',
// the compiler FORCES you to wrap the execution in a try-catch!
try {
readSecureFile();
} catch (FileNotFoundException e) {
System.out.println("The Main API routed a graceful 404 response to the user's browser.");
}
}
}
[!CAUTION] Checked Exceptions vs Unchecked Exceptions: Java requires you to handle (via try/catch or throws) "Checked" exceptions like
IOExceptionat compile time. However, logical "Unchecked" exceptions likeNullPointerExceptionorArithmeticExceptionare completely ignored by the compiler.