Try Catch
Try Catch
A school program needs reliable data and clear rules. A try block contains work that may fail; a matching catch handles the exception. Invalid marks text can produce a helpful message instead of an uncaught failure.
Understand
A try block contains work that may fail; a matching catch handles the exception.
Apply
Trace the Java example, predict its output and explain the result before running it.
Avoid mistakes
Execution does not resume at the failing instruction. It continues after the matching handler when recovery completes normally.
Try Catch
In real-world programming, not everything goes as planned. Files might be missing, users might enter invalid input, or network calls might fail. In Java, rather than allowing your program to crash, you can use try-catch blocks to gracefully handle exceptions.
What is a try-catch Block?
The try-catch block is Java's way of saying: "Try this risky thing, and if it fails, here's what to do." It helps you prevent unexpected termination of your program by catching exceptions and letting you handle them in a user-friendly way.
Syntax of try-catch
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
Example: Divide by Zero
This is one of the most common runtime exceptions. Let’s see how try-catch can help handle it:
public class TryCatchExample {
public static void main(String[] args) {
int a = 10;
int b = 0;
try {
int result = a / b;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
System.out.println("Program continues...");
}
}
Cannot divide by zero!
Program continues...
Explanation:
Java · example discussed here
public class TryCatchExample {
public static void main(String[] args) {
int a = 10;
int b = 0;
try {
int result = a / b;
System.out.println("Result: " + result);
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
System.out.println("Program continues...");
}
}
The division a / b throws an ArithmeticException because b is 0. Without the try-catch, the program would crash. But thanks to the catch block, we handle it and continue execution.
Multiple catch Blocks
Sometimes, more than one type of exception might occur. You can handle each differently:
public class MultipleCatchExample {
public static void main(String[] args) {
try {
int[] arr = new int[3];
arr[5] = 100 / 0;
} catch (ArithmeticException e) {
System.out.println("Arithmetic error occurred.");
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Array index is out of bounds.");
} catch (Exception e) {
System.out.println("General exception caught.");
}
}
}
Array index is out of bounds.
Why the Order of catch Blocks Matters
Java checks the catch blocks in the order they are written. If you place a general Exception block before specific exceptions like ArithmeticException or ArrayIndexOutOfBoundsException, the specific ones will never be reached, causing a compilation error.
Using Exception Object
You can get more details about what went wrong by printing the exception object:
public class ExceptionMessageExample {
public static void main(String[] args) {
try {
String str = null;
System.out.println(str.length());
} catch (NullPointerException e) {
System.out.println("Exception: " + e);
e.printStackTrace();
}
}
}
Exception: java.lang.NullPointerException
java.lang.NullPointerException
at ExceptionMessageExample.main(...)
Best Practices for try-catch
- Catch specific exceptions before general ones.
- Don't use empty catch blocks — always handle or log the error.
- Use
finallyblock (covered in another tutorial) for cleanup actions. - Don’t abuse try-catch to mask bad logic. Validate inputs where possible.
Real-Life Use Case: File Handling
Imagine trying to read from a file that doesn’t exist:
import java.io.*;
public class FileExample {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("nonexistent.txt");
reader.read();
reader.close();
} catch (FileNotFoundException e) {
System.out.println("File not found.");
} catch (IOException e) {
System.out.println("Error reading the file.");
}
}
}
File not found.
Conclusion
The try-catch block is your first line of defense against unpredictable runtime errors. It's not just about avoiding crashes; it's about writing robust, user-friendly Java applications that fail gracefully — or, better yet, recover intelligently.
Important boundaries and mistakes
Execution does not resume at the failing instruction. It continues after the matching handler when recovery completes normally.
Try the school example
Before running this Java program, write down each line you expect to see. Identify the value, branch, object or exception responsible for each line. Then explain whether the following assumption is valid: Execution does not resume at the failing instruction.
Java 17 · Main.java · complete practice program
public class Main {
public static void main(String[] args) {
try {
Integer.parseInt("absent");
}
catch (NumberFormatException e) {
System.out.println("Enter a number");
}
}
}
Worked answer and reasoning
Java 17 · Main.java · source repeated for this answer
public class Main {
public static void main(String[] args) {
try {
Integer.parseInt("absent");
}
catch (NumberFormatException e) {
System.out.println("Enter a number");
}
}
}
Expected output
Enter a numberA try block contains work that may fail; a matching catch handles the exception. Invalid marks text can produce a helpful message instead of an uncaught failure.
Execution does not resume at the failing instruction. It continues after the matching handler when recovery completes normally.
Run with javac Main.java, then java Main. The declaration of Main names the class; main starts the example, and println writes a complete output line.
Check your understanding
Check a common mistake
What to remember
A try block contains work that may fail; a matching catch handles the exception. Invalid marks text can produce a helpful message instead of an uncaught failure. Execution does not resume at the failing instruction. It continues after the matching handler when recovery completes normally.
Related explanations: Java Variables, Java If Statement - Syntax and Examples, Java Class - Blueprint of Objects, Exceptions in Java Introduction.
Supporting documentation: Official Java learning guide and Java 17 language specification.
Reaching the recap and completing the quizzes are separate milestones.