MODULE 1 · TOPIC 5 · VISUAL PROGRAMMING LAB

Exception Handling

Trace how exceptions interrupt normal execution, propagate and reach a handler.

Browser-based simulations: change the inputs, trace the Java statements and inspect results. No arbitrary Java execution, real database, threads or file changes occur here.

1. Try, catch and finally

Test safe division and a zero divisor.

Java example
Program / simulation outputConsole
Live state / data blocksCompact blocks
CurrentResultError / rejected

Inputs above update the example. Highlighted line indicates the current operation. Fragments marked “inside main” or requiring setup belong in the indicated Java project.

What this animation explains

A matching catch handles an exception. finally normally executes on both success and exception; abrupt JVM termination is an exception to that rule.

Try and observe

Change b to 3 and 0. Follow which blocks run.

2. Exception propagation — call stack

See a failure unwind from a method to main.

Java example
Program / simulation outputConsole
Stack frame inspectorCompact blocks
CurrentResultError / rejected

Inputs above update the example. Highlighted line indicates the current operation. Fragments marked “inside main” or requiring setup belong in the indicated Java project.

What this animation explains

An uncaught exception propagates up the stack until a compatible catch is found. Unwound method frames do not resume at their throw site.

Try and observe

Toggle failure and success.

3. Checked exceptions and try-with-resources

Observe automatic resource closure.

Java example
Program / simulation outputConsole
Live state / data blocksCompact blocks
CurrentResultError / rejected

Inputs above update the example. Highlighted line indicates the current operation. Fragments marked “inside main” or requiring setup belong in the indicated Java project.

What this animation explains

IOException is checked and must be caught or declared. A successfully initialized AutoCloseable resource is closed even when its body fails.

Try and observe

Choose missing: no reader was opened. Choose read failure: the opened reader still closes.

4. Hands-on practice and assessment

Programming challenge

Validate a positive age using IllegalArgumentException, catch it at the caller and display a friendly message. Add a file-read example with try-with-resources.

Edit the scratchpad below. Copy your code into an actual Java project or IDE to compile and test it.

Quick assessment

Key points and real Java notes

Use specific exception types; avoid swallowing exceptions. throws declares potential exceptions, throw raises one. Error generally represents serious JVM/system failures.