How to Use Try Catch in Java: Simple Guide with Examples
In Java, use
try to wrap code that might cause an error and catch to handle that error gracefully. This helps your program continue running even if something goes wrong inside the try block.Syntax
The try-catch block has two main parts: try where you put code that might throw an error, and catch where you handle the error if it happens.
You can also add a finally block to run code no matter what, like closing files.
java
try { // code that might throw an exception } catch (ExceptionType name) { // code to handle the exception } finally { // code that always runs (optional) }
Example
This example shows how to catch an error when dividing by zero. The program prints a message instead of crashing.
java
public class TryCatchExample { public static void main(String[] args) { try { int result = 10 / 0; // This will cause an error System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("Cannot divide by zero!"); } finally { System.out.println("This runs no matter what."); } } }
Output
Cannot divide by zero!
This runs no matter what.
Common Pitfalls
- Not catching the right exception type can cause errors to go unhandled.
- Leaving the
catchblock empty hides problems and makes debugging hard. - Using
trywithoutcatchorfinallycauses a compile error.
java
/* Wrong: empty catch hides error */ try { int[] arr = new int[2]; System.out.println(arr[5]); } catch (ArrayIndexOutOfBoundsException e) { // empty catch - bad practice } /* Right: handle error with message */ try { int[] arr = new int[2]; System.out.println(arr[5]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Index is out of range!"); }
Quick Reference
Remember these tips when using try-catch:
- Always catch specific exceptions, not just
Exception. - Use
finallyto clean up resources like files or connections. - Don’t ignore exceptions; handle or log them.
Key Takeaways
Use try to wrap code that might cause errors and catch to handle those errors.
Catch specific exceptions to handle problems clearly and avoid hiding bugs.
Use finally to run code that must execute regardless of errors, like closing resources.
Never leave catch blocks empty; always handle or log exceptions.
Try-catch helps keep your program running smoothly even when errors happen.