exception handling
What is an Exception?
An exception is an event that disrupts the normal flow of a program — usually caused by an error at runtime, such as dividing by zero, accessing an invalid array index, or trying to use a null object. Without handling, an exception crashes your program and prints a stack trace.
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]); // crashes: ArrayIndexOutOfBoundsExceptionThe try-catch Block
To handle an exception gracefully instead of crashing, wrap risky code in a try block and handle the error in a catch block.
try {
int[] numbers = {1, 2, 3};
System.out.println(numbers[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Error: That index doesn't exist in the array.");
}
System.out.println("Program continues running...");Catching Multiple Exception Types
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} catch (Exception e) {
System.out.println("Something else went wrong: " + e.getMessage());
}Java checks each catch block in order and runs the first one that matches the exception's type. A generic catch (Exception e) at the end acts as a safety net for anything not caught earlier.
The finally Block
Code inside finally always runs, whether an exception occurred or not — commonly used for cleanup like closing files or database connections.
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero.");
} finally {
System.out.println("This always runs, error or not.");
}Common Built-in Exceptions
| Exception | When It Happens |
|---|---|
ArithmeticException | Dividing an integer by zero |
ArrayIndexOutOfBoundsException | Accessing an invalid array index |
NullPointerException | Calling a method on a null reference |
NumberFormatException | Converting an invalid string to a number, e.g. Integer.parseInt("abc") |
ClassCastException | Invalid casting between incompatible types |
Checked vs Unchecked Exceptions
- Checked exceptions (like
IOException) must be either caught or declared usingthrows— the compiler enforces this. - Unchecked exceptions (like
NullPointerException) extendRuntimeExceptionand are not checked at compile time.
import java.io.FileReader;
import java.io.IOException;
public void readFile() throws IOException {
FileReader reader = new FileReader("data.txt");
}Throwing Your Own Exceptions
You can manually trigger an exception with throw, which is useful for enforcing rules in your own code.
public class Account {
double balance;
void withdraw(double amount) {
if (amount > balance) {
throw new IllegalArgumentException("Insufficient funds.");
}
balance -= amount;
}
}Creating a Custom Exception
public class InsufficientFundsException extends Exception {
public InsufficientFundsException(String message) {
super(message);
}
}
public class Account {
double balance;
void withdraw(double amount) throws InsufficientFundsException {
if (amount > balance) {
throw new InsufficientFundsException("Not enough balance to withdraw.");
}
balance -= amount;
}
}
Best practice: Only catch exceptions you can meaningfully handle. Avoid emptycatchblocks that silently swallow errors — at minimum, log the error so it doesn't disappear unnoticed.
Course Recap
Congratulations — you've completed the Java Basics course! You now understand:
- How Java code is written, compiled, and run
- Variables, data types, and casting
- Operators and decision-making with if-else and switch
- Loops for repeating logic
- Arrays for storing collections of data
- Methods for organizing reusable code
- Classes, objects, inheritance, and polymorphism
- Exception handling for robust, error-resistant programs
Next steps: From here, explore Java Collections (ArrayList,HashMap), file I/O, and eventually frameworks like Spring Boot for building real-world applications.