Python Java C C++ HTML CSS JS

Java Practice Questions

Topic-based coding problems with sample test cases — build confidence step by step.

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.
A single line with two integers A B.
The quotient, or "Cannot divide by zero".
Sample Input 1
10 2
Sample Output 1
5
Sample Input 2
10 0
Sample Output 2
Cannot divide by zero
-10^6
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.
First line: N. Second line: N ints. Third line: K.
Element or "Index out of range".
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
1
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".
A single line containing a string.
The doubled integer or "Invalid number".
Sample Input 1
21
Sample Output 1
42
Sample Input 2
abc
Sample Output 2
Invalid number
S length
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".
A single integer N.
Inside try, then an error message or no extra line, then Inside finally.
Sample Input 1
5
Sample Output 1
Inside try
Inside finally
Sample Input 2
-1
Sample Output 2
Inside try
Caught exception
Inside finally
Any integer.
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...
First line: a string. Second line: an integer K.
On success the char at K, else the first caught message: "Number format error" or "Index out of range".
Sample Input 1
hello
1
Sample Output 1
e
Sample Input 2
123
5
Sample Output 2
Index out of range
String length
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".
A single line with two integers A B.
The quotient, or "Inner: division error".
Sample Input 1
10 2
Sample Output 1
5
Sample Input 2
10 0
Sample Output 2
Inner: division error
B may be 0.
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".
A single integer age.
Eligible, or the exception message.
Sample Input 1
20
Sample Output 1
Eligible
Sample Input 2
16
Sample Output 2
Not eligible
1
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.
A single line: a file name.
"File created" or "IO error".
Sample Input 1
demo.txt
Sample Output 1
File created
Sample Input 2

                      
Sample Output 2
IO error
Any file name.
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".
A single integer age.
Valid, or Custom: Age must be 18+.
Sample Input 1
22
Sample Output 1
Valid
Sample Input 2
15
Sample Output 2
Custom: Age must be 18+
1
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".
A single integer N.
Ok, or Negative not allowed.
Sample Input 1
10
Sample Output 1
Ok
Sample Input 2
-3
Sample Output 2
Negative not allowed
Any integer.
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.
A single integer N.
Two lines: Finally block, then the result.
Sample Input 1
5
Sample Output 1
Finally block
Positive
Sample Input 2
0
Sample Output 2
Finally block
Non-positive
Any integer.
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".
A single integer N.
"Unchecked caught" or "No exception".
Sample Input 1
1
Sample Output 1
Unchecked caught
Sample Input 2
2
Sample Output 2
No exception
1
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
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");
}
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
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");
}
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
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");
}
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");
}
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");
}
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());
}
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");
}
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");
}
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");
}
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");
}
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");
}
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.