DEV Community

Cover image for Exception Handling Tricky Questions :
Kavitha
Kavitha

Posted on

Exception Handling Tricky Questions :

1.

try {

} finally {

}
Enter fullscreen mode Exit fullscreen mode

Answer: Valid (A try block can have only a finally block without catch.)
2.

try {

} catch(Exception e) {

}
Enter fullscreen mode Exit fullscreen mode

Answer: Valid (A try block can have only a catch block.)
3.

try {

} catch(Exception e) {

} finally {

}
Enter fullscreen mode Exit fullscreen mode

Answer: Valid (A try block can have both catch and finally.)
4.

try {

} catch(ArithmeticException e) {

} catch(Exception e) {

}
**Answer:** Valid (Specific exception comes before general exception.)
Enter fullscreen mode Exit fullscreen mode

5.

**Answer:** Not Valid (General exception must come after specific exception.)
try {

} catch(Exception e) {

} catch(ArithmeticException e) {

}
Enter fullscreen mode Exit fullscreen mode

6.

try {

} finally {

} catch(Exception e) {

}
Enter fullscreen mode Exit fullscreen mode

Answer: Not Valid (catch block must come before finally.)
7.

try {

} catch(ArithmeticException e) {

} finally {

} catch(Exception e) {

}
Enter fullscreen mode Exit fullscreen mode

Answer: Not Valid (catch block cannot come after finally.)
8.

try {

} catch(Exception e) {

} finally {

} finally {

}
Enter fullscreen mode Exit fullscreen mode

Answer: Not Valid (Only one finally block is allowed.)
9.

try {

}
Enter fullscreen mode Exit fullscreen mode

Answer: Not Valid (try must be followed by at least one catch or a finally block.)
10.

catch(Exception e) {

}
Enter fullscreen mode Exit fullscreen mode

Answer: Not Valid (catch cannot exist without a try block.)
11.

finally {

}
Enter fullscreen mode Exit fullscreen mode

Answer: Not Valid (finally cannot exist without a try block.)
12.

try {

} catch(ArithmeticException e) {

} catch(ArithmeticException e) {
**Answer:** Not Valid (Duplicate catch blocks for the same exception are not allowed.)
}
Enter fullscreen mode Exit fullscreen mode

13.

try {

} catch(Exception e) {

} catch(RuntimeException e) {

}
Enter fullscreen mode Exit fullscreen mode

Answer: Not Valid (General exception must come after specific exception.)
14.

try {

} catch(RuntimeException e) {

} catch(Exception e) {

}
Enter fullscreen mode Exit fullscreen mode

Answer: Valid (Specific exception comes before general exception.)
15.

try {

} finally {

} finally {

}
Enter fullscreen mode Exit fullscreen mode

Answer: Not Valid (Only one finally block is allowed.)

Top comments (0)