⬅ Previous Topic
Reflection in JavaNext Topic ⮕
Java try-catch⬅ Previous Topic
Reflection in JavaNext Topic ⮕
Java try-catchWhen you run a Java program, sometimes things go wrong. Maybe you're trying to divide a number by zero, or you're reading a file that doesn't exist. In Java, these "unexpected events" are called exceptions.
An exception is an event that disrupts the normal flow of a program. It’s a runtime error — something Java didn’t expect to happen while your code was running.
For example:
public class DivideByZero {
public static void main(String[] args) {
int result = 10 / 0;
System.out.println("Result: " + result);
}
}
Exception in thread "main" java.lang.ArithmeticException: / by zero
Notice that Java didn’t just crash silently. It gave a detailed message — the type of error and the line where it happened. That’s part of what makes Java’s exception system so developer-friendly.
These are exceptions that Java forces you to handle at compile time. They typically deal with external resources like files, databases, or network connections.
import java.io.File;
import java.io.FileReader;
public class CheckedExample {
public static void main(String[] args) throws Exception {
File file = new File("myfile.txt");
FileReader reader = new FileReader(file); // May throw FileNotFoundException
}
}
Java won't compile this code unless you either handle the exception with a try-catch
block or declare it with throws
.
These are runtime exceptions, and Java does not require you to catch or declare them. Common examples include:
ArithmeticException
NullPointerException
ArrayIndexOutOfBoundsException
public class UncheckedExample {
public static void main(String[] args) {
String str = null;
System.out.println(str.length()); // NullPointerException
}
}
Exception in thread "main" java.lang.NullPointerException
All exceptions are part of the Throwable
class. Here's a simplified view:
This is the most common way to catch exceptions.
public class TryCatchExample {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Caught an exception: " + e.getMessage());
}
}
}
Caught an exception: / by zero
Different exceptions can be caught separately.
public class MultiCatchExample {
public static void main(String[] args) {
try {
int[] nums = {1, 2};
System.out.println(nums[5]);
} catch (ArithmeticException e) {
System.out.println("Arithmetic error");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index error");
}
}
}
Array index error
This block always runs, whether or not there’s an exception. It's used for cleanup operations.
public class FinallyExample {
public static void main(String[] args) {
try {
int x = 5 / 0;
} catch (ArithmeticException e) {
System.out.println("Handled exception.");
} finally {
System.out.println("Finally block always runs.");
}
}
}
Handled exception.
Finally block always runs.
public class ThrowExample {
public static void main(String[] args) {
throw new IllegalArgumentException("This is not allowed!");
}
}
Exception in thread "main" java.lang.IllegalArgumentException: This is not allowed!
If you want to let the caller handle an exception, you can declare it using throws
.
import java.io.FileReader;
public class ThrowsExample {
public static void main(String[] args) throws Exception {
FileReader reader = new FileReader("nofile.txt");
}
}
Exception in thread "main" java.io.FileNotFoundException: nofile.txt (No such file or directory)
try-catch
to handle errors.finally
always runs, perfect for clean-up.throw
is used to raise exceptions manually.throws
passes the responsibility to the caller.⬅ Previous Topic
Reflection in JavaNext Topic ⮕
Java try-catchYou can support this website with a contribution of your choice.
When making a contribution, mention your name, and programguru.org in the message. Your name shall be displayed in the sponsors list.