Bird
Raised Fist0
Javaprogramming~20 mins

Try–catch block in Java - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Try-Catch Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of try-catch with arithmetic exception
What is the output of this Java code snippet?
Java
public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 0;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        }
    }
}
ACompilation error
BResult: 0
CCannot divide by zero
DRuntime error: NullPointerException
Attempts:
2 left
💡 Hint
Think about what happens when dividing by zero in Java.
Predict Output
intermediate
2:00remaining
Output when no exception occurs in try block
What will be printed when this Java code runs?
Java
public class Main {
    public static void main(String[] args) {
        try {
            int result = 10 / 2;
            System.out.println("Result: " + result);
        } catch (ArithmeticException e) {
            System.out.println("Cannot divide by zero");
        }
    }
}
ANo output
BResult: 5
CCannot divide by zero
DCompilation error
Attempts:
2 left
💡 Hint
No exception happens here, so catch block is skipped.
🔧 Debug
advanced
2:00remaining
Identify the error in try-catch syntax
Which option shows the code that will cause a compilation error due to incorrect try-catch syntax?
A
try {
    int x = 5;
} catch (Exception e) {
    System.out.println(e);
}
B
}
;)e(nltnirp.tuo.metsyS    
{ )e noitpecxE( hctac }
;5 = x tni    
{ yrt
C
try {
    int x = 5;
} catch (Exception e) {
    System.out.println(e);
} finally {
    System.out.println("Done");
}
D
try {
    int x = 5;
} catch Exception e {
    System.out.println(e);
}
Attempts:
2 left
💡 Hint
Check the syntax of the catch block parentheses.
Predict Output
advanced
2:00remaining
Output with multiple catch blocks
What will this Java program print?
Java
public class Main {
    public static void main(String[] args) {
        try {
            int[] arr = new int[2];
            System.out.println(arr[5]);
        } catch (ArithmeticException e) {
            System.out.println("Arithmetic Exception caught");
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Array index out of bounds caught");
        } finally {
            System.out.println("Finally block executed");
        }
    }
}
A
Array index out of bounds caught
Finally block executed
B
Arithmetic Exception caught
Finally block executed
CRuntime error: NullPointerException
DNo output
Attempts:
2 left
💡 Hint
Which exception is thrown by accessing arr[5] when arr length is 2?
🧠 Conceptual
expert
2:00remaining
Behavior of try-catch-finally with return statements
What is the output of this Java code?
Java
public class Main {
    public static int test() {
        try {
            return 1;
        } catch (Exception e) {
            return 2;
        } finally {
            return 3;
        }
    }
    public static void main(String[] args) {
        System.out.println(test());
    }
}
A3
B2
CCompilation error
D1
Attempts:
2 left
💡 Hint
Remember that finally block executes even after return statements.

Practice

(1/5)
1. What is the main purpose of a try-catch block in Java?
easy
A. To create new classes
B. To handle errors and prevent program crashes
C. To declare variables
D. To repeat code multiple times

Solution

  1. Step 1: Understand the role of try block

    The try block contains code that might cause an error during execution.
  2. Step 2: Understand the role of catch block

    The catch block runs only if an error occurs, allowing the program to handle it gracefully.
  3. Final Answer:

    To handle errors and prevent program crashes -> Option B
  4. Quick 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
A. try { /* code */ } catch (e) { /* handle */ }
B. try { /* code */ } catch Exception e { /* handle */ }
C. try { /* code */ } catch { /* handle */ }
D. try { /* code */ } catch (Exception e) { /* handle */ }

Solution

  1. Step 1: Check catch syntax

    The catch block must specify the exception type in parentheses, like catch (Exception e).
  2. Step 2: Identify correct option

    try { /* code */ } catch (Exception e) { /* handle */ } correctly uses parentheses and exception type; others miss parentheses or type.
  3. Final Answer:

    try { /* code */ } catch (Exception e) { /* handle */ } -> Option D
  4. Quick 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
A. Error caught
B. Result: 0
C. 5
D. Compilation error

Solution

  1. Step 1: Identify the error in try block

    Dividing by zero causes an ArithmeticException at runtime.
  2. Step 2: Check catch block response

    The catch block catches ArithmeticException and prints "Error caught".
  3. Final Answer:

    Error caught -> Option A
  4. Quick 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
A. Array size is too small
B. No error, code runs fine
C. Catch block syntax is wrong
D. Exception type is incorrect

Solution

  1. Step 1: Analyze array usage

    Array declared with size 3, valid indices are 0,1,2; index 5 is out of bounds.
  2. Step 2: Understand exception thrown

    Accessing index 5 causes ArrayIndexOutOfBoundsException, which is correctly caught.
  3. Final Answer:

    Array size is too small -> Option A
  4. Quick 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
A. Missing finally block causes error
B. Should catch IOException instead of Exception
C. Correctly handles invalid input with try-catch
D. Try block should be outside Scanner usage

Solution

  1. Step 1: Understand input reading

    Using sc.nextInt() reads integer input; invalid input throws InputMismatchException, a subclass of Exception.
  2. Step 2: Check try-catch usage

    The try block attempts input; catch block handles any Exception, printing "Invalid input" if input is wrong.
  3. Final Answer:

    Correctly handles invalid input with try-catch -> Option C
  4. Quick 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