1. Why do we need try-catch?
As you already know, in programming errors happen all the time: division by zero, invalid input, missing file, etc. If you don’t handle such situations, the program will terminate with an error (crash).
The try-catch construct lets you “catch” an exception and prevent the program from crashing by handling the error gracefully.
Syntax of the try-catch construct
try
{
// Code that may throw an exception
}
catch (TipIsklyucheniya imyaPeremennoy)
{
// Code to handle the exception
}
Explanation:
- try — “try to execute this code”.
- catch — “if an exception of the specified type occurs, handle it here”.
How does it work?
If an exception occurs inside the try block, execution of that block stops immediately and control is transferred to the first matching catch block. If no exception occurs, the catch block is skipped.
2. Example: division by zero
Without exception handling
int a = 10;
int b = 0;
int result = a / b; // The program will crash here!
System.out.println("Result: " + result); // We won't get this far
Result:
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Main.main(Main.java:3)
With try-catch handling
int a = 10;
int b = 0;
try
{
int result = a / b; // An exception may occur here
System.out.println("Result: " + result);
}
catch (ArithmeticException e)
{
System.out.println("Error: cannot divide by zero!");
}
System.out.println("The program continued running.");
Result:
Error: cannot divide by zero!
The program continued running.
Explanation:
- As soon as Java encounters division by zero, it “throws” an exception.
- The try block is interrupted and control passes to catch.
- After handling the error, the program continues execution.
3. How the catch block works
In the parentheses after catch, you specify the exception type (for example, ArithmeticException) and a variable name (usually e).
Inside the catch block you can get details about the error:
- e.getMessage() — a short description of the error.
- e.printStackTrace() — detailed information (for debugging).
Example:
try
{
int[] arr = new int[2];
int x = arr[10]; // Error: index does not exist
}
catch (ArrayIndexOutOfBoundsException e)
{
System.out.println("Error: " + e.getMessage()); // Print the error message
e.printStackTrace(); // Print full error details to the console
}
4. Execution flow when an exception occurs
If there are no errors in the try block, the catch block is skipped.
If an error occurs in the try block, execution is interrupted at the point of the error and control immediately transfers to the first matching catch. Anything after the error inside try will not execute!
Illustration:
try
{
System.out.println("1. Start of try");
int a = 10 / 0; // Error!
System.out.println("2. After division"); // Won't execute
}
catch (ArithmeticException e)
{
System.out.println("3. Inside catch block");
}
System.out.println("4. After try-catch");
Result:
1. Start of try
3. Inside catch block
4. After try-catch
5. Common mistakes when using try-catch
Error No. 1: A too-broad catch.
If you use catch (Exception e), you may intercept a bunch of unexpected errors that you cannot handle correctly.
Solution: catch only those exceptions that are actually expected at this point (for example, IOException, SQLException).
Error No. 2: An empty catch.
Writing catch (Exception e) {} means hiding the problem. The program will crash somewhere else or behave strangely.
Solution: at least log the error (e.printStackTrace() or a logger).
Error No. 3: Believing that try-catch will fix any problem.
If the error is in the program’s logic (for example, division by zero, an incorrect algorithm), no try-catch will help.
Solution: use try-catch only for truly expected situations, not to mask bugs.
GO TO FULL VERSION