A try-catch block helps your program handle errors without crashing. It lets you try some code and catch problems if they happen.
Try–catch block in Java
Introduction
Syntax
Java
try { // code that might cause an error } catch (ExceptionType name) { // code to handle the error }
The try block contains code that might cause an error.
The catch block runs only if an error happens in the try block.
Examples
Java
try { int result = 10 / 0; } catch (ArithmeticException e) { System.out.println("Cannot divide by zero."); }
Java
try { String text = null; System.out.println(text.length()); } catch (NullPointerException e) { System.out.println("Text is null."); }
Sample Program
This program tries to access an array element that does not exist. The catch block handles the error and the program keeps running.
Java
public class TryCatchExample { public static void main(String[] args) { try { int[] numbers = {1, 2, 3}; System.out.println(numbers[5]); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Oops! Index is out of range."); } System.out.println("Program continues smoothly."); } }
Important Notes
You can have multiple catch blocks to handle different errors.
Try-catch blocks help keep your program from stopping unexpectedly.
Summary
Use try-catch to handle errors safely.
The try block runs code that might fail.
The catch block runs if an error happens, letting you respond nicely.
Practice
1. What is the main purpose of a
try-catch block in Java?easy
Solution
Step 1: Understand the role of try block
The try block contains code that might cause an error during execution.Step 2: Understand the role of catch block
The catch block runs only if an error occurs, allowing the program to handle it gracefully.Final Answer:
To handle errors and prevent program crashes -> Option BQuick Check:
try-catch handles errors = D [OK]
Hint: Try-catch is for error handling, not loops or declarations [OK]
Common Mistakes:
- Confusing try-catch with loops
- Thinking try-catch declares variables
- Assuming try-catch creates classes
2. Which of the following is the correct syntax to catch an exception in Java?
easy
Solution
Step 1: Check catch syntax
The catch block must specify the exception type in parentheses, likecatch (Exception e).Step 2: Identify correct option
try { /* code */ } catch (Exception e) { /* handle */ } correctly uses parentheses and exception type; others miss parentheses or type.Final Answer:
try { /* code */ } catch (Exception e) { /* handle */ } -> Option DQuick Check:
Correct catch syntax = A [OK]
Hint: Catch must have parentheses with exception type [OK]
Common Mistakes:
- Omitting parentheses in catch
- Not specifying exception type
- Using wrong catch syntax
3. What will be the output of this code?
try {
int a = 5 / 0;
System.out.println("Result: " + a);
} catch (ArithmeticException e) {
System.out.println("Error caught");
}medium
Solution
Step 1: Identify the error in try block
Dividing by zero causes anArithmeticExceptionat runtime.Step 2: Check catch block response
The catch block catchesArithmeticExceptionand prints "Error caught".Final Answer:
Error caught -> Option AQuick Check:
Division by zero triggers catch = A [OK]
Hint: Division by zero triggers catch block output [OK]
Common Mistakes:
- Expecting normal output despite error
- Thinking code crashes without catch
- Confusing compile-time and runtime errors
4. Find the error in this code snippet:
try {
int[] arr = new int[3];
arr[5] = 10;
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index error");
}medium
Solution
Step 1: Analyze array usage
Array declared with size 3, valid indices are 0,1,2; index 5 is out of bounds.Step 2: Understand exception thrown
Accessing index 5 causesArrayIndexOutOfBoundsException, which is correctly caught.Final Answer:
Array size is too small -> Option AQuick Check:
Index 5 invalid for size 3 = C [OK]
Hint: Check array size vs accessed index to find error [OK]
Common Mistakes:
- Thinking catch syntax is wrong
- Assuming no error occurs
- Confusing exception types
5. You want to read an integer from user input safely. Which code correctly uses try-catch to handle invalid input?
import java.util.Scanner;
Scanner sc = new Scanner(System.in);
int num;
try {
num = sc.nextInt();
System.out.println("You entered: " + num);
} catch (Exception e) {
System.out.println("Invalid input");
}hard
Solution
Step 1: Understand input reading
Usingsc.nextInt()reads integer input; invalid input throwsInputMismatchException, a subclass of Exception.Step 2: Check try-catch usage
The try block attempts input; catch block handles any Exception, printing "Invalid input" if input is wrong.Final Answer:
Correctly handles invalid input with try-catch -> Option CQuick Check:
Try-catch handles input errors = B [OK]
Hint: Catch Exception to handle all input errors safely [OK]
Common Mistakes:
- Thinking finally is mandatory
- Catching wrong exception type
- Placing try block incorrectly
Recommended
Ready to prove it?
Pass the test and this pattern moves unknown
10 questions ~5 mineasy hard
