1. Getting to know exceptions
Let’s start with a simple analogy. Imagine your program is a car driving down the road. Everything is fine until something unexpected happens: a flat tire, an empty gas tank, an overheated engine. If you don’t “handle” this situation (for example, put on the spare or refuel), the car will stop and won’t go any farther. The same is true in a program: if you don’t handle an exception, the program will terminate abnormally.
An exception (exception) is an object that is created at the moment some problem occurs while the program is running. The exception says: “Stop! Something went wrong!”
Examples of situations that cause exceptions:
- Division by zero (10 / 0)
- Trying to access a non-existent array element (arr[999])
- Opening a file that doesn’t exist on disk
- Converting the string "abc" to a number (Integer.parseInt("abc"))
Important: Exceptions are not compilation errors (such as typos in code) but problems that occur while the program is running.
Why are exceptions good?
- Clean code: The main program logic isn’t cluttered with constant checks for every little thing.
- Flexibility: You can handle errors centrally (for example, all file-reading errors in one place).
- Reliability: The program doesn’t “crash” with a cryptic message; it reports exactly what happened.
2. Exceptions (Exceptions) vs Errors (Errors)
In Java, there are two main kinds of problems that can occur while the program is running:
Errors (Errors)
Errors are fatal, unrecoverable problems caused by failures in the Java Virtual Machine (JVM) itself. They’re usually related to machine resources or internal JVM failures.
Examples of errors:
- OutOfMemoryError — ran out of memory.
- StackOverflowError — stack overflow (for example, due to infinite recursion).
Important: You generally shouldn’t try to handle such errors in your program.
Exceptions (Exceptions)
Exceptions are problems the program can (and should) deal with. They arise due to bugs in program logic or due to external factors (for example, the user entered something unexpected).
Examples of exceptions:
- NullPointerException — attempting to use null as an object.
- ArrayIndexOutOfBoundsException — array index out of bounds.
- IOException — an error during file I/O.
There are two kinds of exceptions in Java:
- Checked exceptions — the compiler requires you to handle them (for example, IOException).
- Unchecked exceptions — the compiler doesn’t require handling (for example, NullPointerException).
Diagram: where everything fits
graph TD
Throwable --> Error
Throwable --> Exception
Exception --> RuntimeException
Exception --> Checked["(other Exceptions)"]
style Throwable fill:#ffa64d,color:#000
style Exception fill:#ffa64d,color:#000
style Checked fill:#ffa64d,color:#000
style Error fill:#ff4d4d,color:#fff
style RuntimeException fill:#4dff88,color:#000
Explanation:
- Throwable — the root of the entire error/exception hierarchy in Java.
- Error — fatal JVM errors; not handled.
- Exception — “normal” exceptions that you can and should handle.
- RuntimeException — unchecked exceptions (programmer errors).
3. What does it look like in code?
Example 1: Division by zero
public class ExceptionDemo
{
public static void main(String[] args)
{
int a = 10;
int b = 0;
int c = a / b; // An ArithmeticException will occur here!
System.out.println("Result: " + c);
}
}
What will happen?
The program will terminate with an error, and you’ll see the message:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at ExceptionDemo.main(ExceptionDemo.java:5)
Example 2: Accessing a non-existent array element
int[] arr = {1, 2, 3};
System.out.println(arr[10]); // ArrayIndexOutOfBoundsException
Example 3: Working with files
import java.io.FileReader;
import java.io.IOException;
public class FileDemo
{
public static void main(String[] args) throws IOException
{
FileReader reader = new FileReader("nofile.txt"); // FileNotFoundException (checked)
int data = reader.read();
System.out.println(data);
reader.close();
}
}
Next, we’ll look at how to handle such exceptional situations cleanly.
GO TO FULL VERSION