Java Exception Handling Practice
try-catch, checked vs unchecked exceptions, custom exceptions and throws.
1
Arithmetic Exception
Easy
Read two integers A and B. If B is 0, print "Cannot divide by zero"; otherwise print A / B. Use a try-catch around the division.
Input Format
A single line with two integers A B.
Output Format
The quotient, or "Cannot divide by zero".
Sample Test Cases
|
Sample Input 1
10 2 |
Sample Output 1
5 |
|
Sample Input 2
10 0 |
Sample Output 2
Cannot divide by zero |
Constraints
-10^6
Explanation
Catch ArithmeticException.
2
Array Index Exception
Easy
Read N, then N integers, then an index K. Print the element at K; if K is out of range print "Index out of range". Use try-catch.
Input Format
First line: N. Second line: N ints. Third line: K.
Output Format
Element or "Index out of range".
Sample Test Cases
|
Sample Input 1
3 10 20 30 1 |
Sample Output 1
20 |
|
Sample Input 2
3 10 20 30 9 |
Sample Output 2
Index out of range |
Constraints
1
Explanation
Catch ArrayIndexOutOfBoundsException.
3
Number Format Exception
Easy
Read a string S. Try to parse it as an integer with Integer.parseInt. On success print the number times 2; on failure print "Invalid number".
Input Format
A single line containing a string.
Output Format
The doubled integer or "Invalid number".
Sample Test Cases
|
Sample Input 1
21 |
Sample Output 1
42 |
|
Sample Input 2
abc |
Sample Output 2
Invalid number |
Constraints
S length
Explanation
Catch NumberFormatException.
1
Try-Catch-Finally
Medium
Read an integer N. Print "Inside try" before any operation. If N is negative, the code throws IllegalArgumentException. Always print "Inside finally".
Input Format
A single integer N.
Output Format
Inside try, then an error message or no extra line, then Inside finally.
Sample Test Cases
|
Sample Input 1
5 |
Sample Output 1
Inside try Inside finally |
|
Sample Input 2
-1 |
Sample Output 2
Inside try Caught exception Inside finally |
Constraints
Any integer.
Explanation
finally always runs.
2
Multiple Catch Blocks
Medium
Read a string and an index K. Try Integer.parseInt(string) (may throw NumberFormatException) then charAt(K) on the result string...
Input Format
First line: a string. Second line: an integer K.
Output Format
On success the char at K, else the first caught message: "Number format error" or "Index out of range".
Sample Test Cases
|
Sample Input 1
hello 1 |
Sample Output 1
e |
|
Sample Input 2
123 5 |
Sample Output 2
Index out of range |
Constraints
String length
Explanation
Order catch blocks from specific to general.
3
Nested Try
Medium
Read two integers A and B. Use an outer try with an inner try that divides A by B. If B is 0, the inner catch prints "Inner: division error"; the outer catch prints "Outer: caught".
Input Format
A single line with two integers A B.
Output Format
The quotient, or "Inner: division error".
Sample Test Cases
|
Sample Input 1
10 2 |
Sample Output 1
5 |
|
Sample Input 2
10 0 |
Sample Output 2
Inner: division error |
Constraints
B may be 0.
Explanation
Inner catches its own exception first.
4
Throwing an Exception
Medium
Read an age. If it is below 18, throw an IllegalArgumentException with message "Not eligible"; catch it in main and print the message. Otherwise print "Eligible".
Input Format
A single integer age.
Output Format
Eligible, or the exception message.
Sample Test Cases
|
Sample Input 1
20 |
Sample Output 1
Eligible |
|
Sample Input 2
16 |
Sample Output 2
Not eligible |
Constraints
1
Explanation
throw new IllegalArgumentException(...).
1
Checked Exception (File)
Hard
Read a file name. Try to create a new File(name) and call createNewFile() inside a try-catch for IOException. Print "File created" on success (ignore the boolean) or "IO error" on failure.
Input Format
A single line: a file name.
Output Format
"File created" or "IO error".
Sample Test Cases
|
Sample Input 1
demo.txt |
Sample Output 1
File created |
|
Sample Input 2
|
Sample Output 2
IO error |
Constraints
Any file name.
Explanation
createNewFile() throws IOException (checked).
2
Custom Exception
Hard
Create a custom exception class InvalidAgeException extends Exception. In main, read age; if < 18 throw it (declared via throws on main or caught) and print "Custom: "; else print "Valid".
Input Format
A single integer age.
Output Format
Valid, or Custom: Age must be 18+.
Sample Test Cases
|
Sample Input 1
22 |
Sample Output 1
Valid |
|
Sample Input 2
15 |
Sample Output 2
Custom: Age must be 18+ |
Constraints
1
Explanation
Your custom class extends Exception.
3
Exception Propagation
Hard
Write a method static void check(int n) that throws IllegalArgumentException when n is negative. main calls check(N) inside try-catch. If N is negative the message is "Negative not allowed"; otherwise print "Ok".
Input Format
A single integer N.
Output Format
Ok, or Negative not allowed.
Sample Test Cases
|
Sample Input 1
10 |
Sample Output 1
Ok |
|
Sample Input 2
-3 |
Sample Output 2
Negative not allowed |
Constraints
Any integer.
Explanation
Propagate with throw, handle in main.
4
Finally with Return
Hard
Write a method static String test(int n) that returns "Positive" for n > 0 else "Non-positive", but always prints "Finally block" before returning (use finally). Print the method result.
Input Format
A single integer N.
Output Format
Two lines: Finally block, then the result.
Sample Test Cases
|
Sample Input 1
5 |
Sample Output 1
Finally block Positive |
|
Sample Input 2
0 |
Sample Output 2
Finally block Non-positive |
Constraints
Any integer.
Explanation
finally executes even before return.
5
Unchecked vs Checked
Hard
Read an integer N. If N == 1, cause an ArrayIndexOutOfBoundsException and catch it, printing "Unchecked caught". Otherwise print "No exception".
Input Format
A single integer N.
Output Format
"Unchecked caught" or "No exception".
Sample Test Cases
|
Sample Input 1
1 |
Sample Output 1
Unchecked caught |
|
Sample Input 2
2 |
Sample Output 2
No exception |
Constraints
1
Explanation
Runtime exceptions need no throws clause.
Competitive MCQs — Java Exception Handling
Code snippets, output prediction, concepts & error spotting. Pick an answer to see instant feedback.
Score
0/ 33
Q1
Which keyword starts a block that may throw an exception?
Correct!
Wrong — correct answer is .
Code that may fail is wrapped in a try block.
Q2
Which keyword catches an exception?
Correct!
Wrong — correct answer is .
Java uses try-catch; except is Python.
Q3
What is the output of this code?
java
1
2
3
4
5
2
3
4
5
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error");
}Correct!
Wrong — correct answer is .
10 / 0 throws ArithmeticException, caught → "Error".
Q4
What is the output of this code?
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error");
}
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error");
}
Correct!
Wrong — correct answer is .
10 / 0 throws ArithmeticException, caught → "Error".
Q5
Which block always executes after try/catch?
Correct!
Wrong — correct answer is .
finally runs regardless of whether an exception occurred.
Q6
Which is the base class of all checked exceptions?
Correct!
Wrong — correct answer is .
Exception is the base of checked exceptions.
Q7
What is the output of this code?
java
1
2
3
4
5
6
2
3
4
5
6
int[] a = {1, 2};
try {
System.out.println(a[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Bad index");
}Correct!
Wrong — correct answer is .
a[5] throws ArrayIndexOutOfBoundsException → "Bad index".
Q8
What is the output of this code?
int[] a = {1, 2};
try {
System.out.println(a[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Bad index");
}
int[] a = {1, 2};
try {
System.out.println(a[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Bad index");
}
Correct!
Wrong — correct answer is .
a[5] throws ArrayIndexOutOfBoundsException → "Bad index".
Q9
Which keyword deliberately throws an exception?
Correct!
Wrong — correct answer is .
throw creates/exits with an exception; throws declares them.
Q10
What is the difference between checked and unchecked exceptions?
Correct!
Wrong — correct answer is .
Checked exceptions are enforced by the compiler.
Q11
Which is an unchecked (runtime) exception?
Correct!
Wrong — correct answer is .
NullPointerException extends RuntimeException (unchecked).
Q12
What is the output of this code?
java
1
2
3
4
5
2
3
4
5
try {
System.out.print("A");
} finally {
System.out.print("B");
}Correct!
Wrong — correct answer is .
Both run — finally needs no exception to execute.
Q13
What is the output of this code?
try {
System.out.print("A");
} finally {
System.out.print("B");
}
try {
System.out.print("A");
} finally {
System.out.print("B");
}
Correct!
Wrong — correct answer is .
Both run — finally needs no exception to execute.
Q14
What is the output of this code?
try {
int[] a = new int[2];
System.out.println(a[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("caught");
}
try {
int[] a = new int[2];
System.out.println(a[5]);
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("caught");
}
Correct!
Wrong — correct answer is .
a[5] is out of bounds and caught by the handler.
Q15
What does the finally block guarantee?
Correct!
Wrong — correct answer is .
finally executes in all paths for cleanup.
Q16
Which exception is thrown for dividing an int by zero?
Correct!
Wrong — correct answer is .
Integer division by zero throws ArithmeticException.
Q17
What is the output of this code?
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("math");
} catch (Exception e) {
System.out.println("any");
}
try {
int x = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("math");
} catch (Exception e) {
System.out.println("any");
}
Correct!
Wrong — correct answer is .
ArithmeticException matches the first catch.
Q18
What is an unchecked exception?
Correct!
Wrong — correct answer is .
Unchecked exceptions extend RuntimeException.
Q19
Which of these is checked?
Correct!
Wrong — correct answer is .
IOException is checked; the others are runtime exceptions.
Q20
What is the output of this code?
try {
throw new IllegalStateException("bad");
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
try {
throw new IllegalStateException("bad");
} catch (IllegalStateException e) {
System.out.println(e.getMessage());
}
Correct!
Wrong — correct answer is .
getMessage() returns the message "bad".
Q21
Which keyword declares that a method may throw a checked exception?
Correct!
Wrong — correct answer is .
throws appears in the method signature to declare checked exceptions.
Q22
Which keyword actually raises an exception?
Correct!
Wrong — correct answer is .
throw new Exception() creates and raises an exception.
Q23
What is the output of this code?
try {
System.out.print("1");
return;
} finally {
System.out.print("2");
}
try {
System.out.print("1");
return;
} finally {
System.out.print("2");
}
Correct!
Wrong — correct answer is .
finally runs before the return completes, printing 2.
Q24
What is the base class for checked exceptions?
Correct!
Wrong — correct answer is .
Checked exceptions derive from Exception (excluding RuntimeException).
Q25
What is the output of this code?
String s = null;
try {
System.out.println(s.length());
} catch (NullPointerException e) {
System.out.println("null");
}
String s = null;
try {
System.out.println(s.length());
} catch (NullPointerException e) {
System.out.println("null");
}
Correct!
Wrong — correct answer is .
Calling length() on null throws NullPointerException.
Q26
What does printStackTrace() do?
Correct!
Wrong — correct answer is .
It logs the stack trace for debugging.
Q27
What is the output of this code?
try {
int x = Integer.parseInt("12a");
} catch (NumberFormatException e) {
System.out.println("nf");
}
try {
int x = Integer.parseInt("12a");
} catch (NumberFormatException e) {
System.out.println("nf");
}
Correct!
Wrong — correct answer is .
Parsing "12a" fails and throws NumberFormatException.
Q28
Which block is optional in try-catch?
Correct!
Wrong — correct answer is .
A try must have at least one catch or finally; each is otherwise optional.
Q29
What is a multi-catch?
Correct!
Wrong — correct answer is .
catch (A | B e) handles several types with one handler.
Q30
What is the output of this code?
try {
throw new RuntimeException("r");
} catch (RuntimeException e) {
System.out.println("runtime");
}
try {
throw new RuntimeException("r");
} catch (RuntimeException e) {
System.out.println("runtime");
}
Correct!
Wrong — correct answer is .
The RuntimeException is caught and prints "runtime".
Q31
Which is the parent of all exceptions and errors?
Correct!
Wrong — correct answer is .
Throwable is the root for both Exception and Error.
Q32
What is the output of this code?
try {
System.out.println("try");
} catch (Exception e) {
System.out.println("catch");
}
try {
System.out.println("try");
} catch (Exception e) {
System.out.println("catch");
}
Correct!
Wrong — correct answer is .
No exception is thrown, so only "try" prints.
Q33
What is an Error in Java exception hierarchy?
Correct!
Wrong — correct answer is .
Errors signal serious system problems usually not meant to be caught.