Exception & Error Handling MCQs for the NSCT
Exception handling is how a program detects a run-time error, jumps to code that deals with it, and cleans up on the way: try/catch/finally in Java, C++ and JavaScript, and try/except/else/finally in Python. It is the eleventh of 16 topics in the Programming (C++/Java/Python) area, which carries 10% of the NSCT according to HEC's Areas of Competencies.
Most questions here are output traces: which lines print, in what order, and what finally does to a return value. The rest test Java's checked and unchecked exceptions. Cleanup ties back to memory management, because exceptions are a common cause of leaks.
Try, catch and finally
An exception is an object that signals an abnormal event, such as dividing by zero or opening a missing file. Code that may fail goes in try. When something is thrown (raised, in Python), the rest of the try block is skipped and the first matching handler runs. finally runs on every exit: normal, by exception, or by return, break or continue.
try:
print("A")
x = 1 / 0 # raises ZeroDivisionError
print("B") # skipped
except ZeroDivisionError:
print("C")
finally:
print("D") # output: A, C, D
Python adds else, which runs only when the try block raised nothing. It keeps the try block small, so the handler cannot catch errors it was not meant for.
| Language | Raise | Handle | Always runs |
|---|---|---|---|
| Java | throw |
catch (Type e) |
finally, try-with-resources |
| C++ | throw |
catch (const Type& e), catch (...) |
destructors (RAII); no finally |
| Python | raise |
except Type as e |
finally, with |
| JavaScript | throw |
catch (e) |
finally |
Exam angle: handlers are tested top to bottom and the first match wins. Put subclasses before superclasses. Java rejects the reverse order at compile time; Python silently runs the broader handler.
Finally and return values
finally runs after a return expression has been evaluated but before the method actually returns. Two rules follow, and they behave the same way in Java and JavaScript:
Code in f() |
Returns |
|---|---|
int x = 10; try { return x; } finally { x = 20; } |
10, because the value was already saved |
try { return 1; } finally { return 2; } |
2, because finally's return replaces it |
Returning or throwing from finally also discards any exception in flight, so style guides forbid it. Python 3.14 even warns about return inside finally.
Exam angle: a finally that only changes a variable never changes a value that has already been returned.
Checked vs unchecked exceptions (Java)
In Java every throwable class descends from Throwable, which has two branches: Exception and Error.
| Kind | Classes | Compiler rule | Example |
|---|---|---|---|
| Checked | Exception except RuntimeException |
Catch it or declare it with throws |
IOException, SQLException |
| Unchecked | RuntimeException and its subclasses |
No rule | NullPointerException, ArithmeticException |
| Unchecked | Error and its subclasses |
No rule; usually not caught | OutOfMemoryError, StackOverflowError |
public void read() throws IOException {
FileReader r = new FileReader("a.txt"); // checked: must catch or declare
}
throw raises one exception; throws in a signature declares what may escape. An overriding method may declare the same checked exceptions, narrower ones or none, but never broader ones. C++, Python and JavaScript have no checked exceptions at all.
Exam angle: use checked exceptions for problems a caller can recover from, such as a missing file, and unchecked ones for programming bugs, such as IllegalArgumentException for a bad argument.
Common traps
- Thinking
finallyis skipped afterreturnorcontinue. It still runs. - Writing
except Exceptionand expecting it to catchsys.exit().SystemExitderives fromBaseException. - Assuming a thrown
intin C++ matchescatch (double). Handlers apply no numeric conversions. - Calling
NullPointerExceptionchecked because it must be "handled". It is aRuntimeException. - Listing a subclass and its parent in one Java multi-catch, such as
FileNotFoundException | IOException. This is a compile error. - Swallowing exceptions with an empty handler or a fake default value, which hides real bugs.
Worked examples
1. Understanding. In Java, is ArithmeticException checked or unchecked?
Answer: unchecked. It extends RuntimeException, so the compiler does not require it to be caught or declared.
2. Application. In Python, what does this print: try: d = {}; d["k"] then except KeyError: print("K") then else: print("E") then finally: print("F")?
Answer: K, then F. The lookup raises KeyError, so its handler runs and else is skipped; finally always runs.
3. Analysis. A Java method opens two resources with try-with-resources, and the body throws. In what order do the close calls and the catch block run? Answer: the resources close in reverse order of opening, then the catch block runs. Closing happens as the try block exits, before any catch or finally of the same statement.
Practise
The quiz below has 100 questions on this topic, filterable by tier and difficulty.
Practise: 100 questions
FAQs
What is the difference between an error and an exception?
In Java both are Throwables: Exception covers conditions a program may reasonably handle, while Error signals serious problems such as OutOfMemoryError that applications normally should not catch. In everyday speech, "error" also means a compile-time mistake, such as a syntax error, which is not an exception at all.
Does C++ have a finally block?
No. C++ relies on RAII instead: put cleanup in a destructor, and it runs automatically when the object goes out of scope, including during stack unwinding after a throw. That is why std::vector, std::unique_ptr and std::lock_guard are exception-safe without a finally.
When should I raise my own exception class?
Create one when callers need to tell your error apart from built-in ones, such as InsufficientFunds in a banking module. In Python inherit from Exception; in Java extend Exception for a checked exception or RuntimeException for an unchecked one. Give it a clear message.
Is it bad to catch every exception?
Catching everything, such as catch (Exception e) or a bare except:, hides bugs you did not expect and can swallow interrupts. Catch the specific exceptions you can actually handle, and let the rest propagate to a top-level handler that logs them. Our debugging and testing page shows how to trace them.
Next step
Move on to Modules, Packages & Libraries MCQs, see all topics on the Programming MCQs hub, or test yourself in an NSCT mock test.