Exception

Comprehensive study notes, diagrams, and exam preparation for Exception.

Exception

Definition

An exception is a runtime abnormal condition or error event that occurs during program execution and disrupts the normal sequence of instructions. It is typically represented as an object or event that can be detected, handled, or propagated using mechanisms such as try, catch, throw, and finally.

In simple words, an exception is a signal that something went wrong while the program was running, and special code is needed to handle that situation.


Main Content

1. First Concept: Types of Exceptions

Checked exceptions

  • These are exceptions that the compiler requires the programmer to handle explicitly.
  • They usually represent conditions that are outside the direct control of the program, such as file access problems or network failures.
  • Example: If a program tries to open a file that may not exist, it must handle the possibility of failure.
  • In languages like Java, checked exceptions must either be caught using a catch block or declared using throws.

Unchecked exceptions

  • These are exceptions that occur at runtime and are not forced by the compiler to be handled.
  • They usually result from programming mistakes such as null references, invalid array indexing, or illegal arithmetic operations.
  • Example: Dividing an integer by zero or calling a method on a null object reference.
  • They often indicate bugs that should be fixed in the program logic rather than simply caught and ignored.

2. Second Concept: Exception Handling Mechanism

Try block

  • The code that may generate an exception is placed inside a try block.
  • This allows the program to monitor risky operations without stopping immediately.
  • Example: Reading user input or accessing a file.

Catch block

  • If an exception occurs inside the try block, the control transfers to a corresponding catch block.
  • The catch block contains code to handle the error, such as displaying a message or using a fallback value.
  • Multiple catch blocks may be used to handle different exception types separately.

Finally block

  • The finally block contains code that must execute whether an exception occurs or not.
  • It is commonly used to release resources such as closing files, database connections, or network streams.
  • Even if an error occurs, the finally block helps ensure cleanup happens properly.

Example flow:

try  ---> risky code
  |
  | if error occurs
  v
catch ---> handle error
  |
  v
finally ---> cleanup

3. Third Concept: Throwing and Propagating Exceptions

Throwing an exception

  • A program can explicitly create and raise an exception when it detects an invalid condition.
  • This is useful when input validation fails or business rules are violated.
  • Example: A bank application may throw an exception if a withdrawal amount is greater than the account balance.
  • Throwing helps signal errors at the exact point where the problem is detected.

Propagation

  • If an exception is not handled in the current method or block, it moves upward to the calling function or method.
  • This is called propagation, and it continues until a matching handler is found.
  • If no handler exists, the program may terminate with an error message.
  • Propagation allows lower-level code to report problems while higher-level code decides how to respond.

Custom exceptions

  • Programmers can define their own exception types for application-specific errors.
  • This improves clarity and makes error handling more meaningful.
  • Example: InsufficientBalanceException, InvalidAgeException, or StudentNotFoundException.
  • Custom exceptions are especially useful in large systems where generic errors are not descriptive enough.

Working / Process

1. A risky operation is executed

  • The program enters a try block and runs statements that may fail.
  • These operations may include file access, user input, arithmetic operations, or communication with external systems.
  • Example: Attempting to read a line from a file.

2. An exception is detected

  • If something abnormal occurs, the runtime system creates an exception object or error signal.
  • The normal sequence of execution is interrupted at that point.
  • The program does not continue line by line in the try block once the exception happens.

3. Handling or propagation occurs

  • The runtime looks for a matching catch block to handle the exception.
  • If found, the handler runs and the program may continue safely.
  • If not found locally, the exception is propagated to the calling method.
  • After handling, the finally block runs for cleanup if it exists.

Example process:

Start
  |
  v
Execute risky code in try
  |
  +--> No exception --> Continue normal execution
  |
  +--> Exception occurs --> Search for catch handler
                                |
                                +--> Handler found --> Handle error --> finally --> Continue/End
                                |
                                +--> No handler --> Propagate upward --> Program may terminate

Advantages / Applications

Improves program reliability

  • Exceptions allow programs to survive unexpected problems without crashing immediately.
  • This makes software more stable and user-friendly.
  • Example: A web application can show an error page instead of failing completely.

Separates normal logic from error handling

  • Exception handling keeps the main code cleaner and easier to read.
  • Error-handling code is placed separately from the core program logic.
  • This improves maintainability and reduces confusion in complex programs.

Useful in real-world applications

  • Exceptions are widely used in file handling, database operations, networking, input validation, and device communication.
  • They help manage conditions that cannot always be predicted in advance.
  • Example: Logging in to an account may involve handling invalid passwords, connection errors, and missing user records.

Summary

  • An exception is an abnormal event that interrupts normal program execution.
  • It is handled using mechanisms like try, catch, finally, and throw.
  • Exceptions help programs respond safely to unexpected errors and continue execution when possible.
  • Important terms to remember: exception, try, catch, finally, throw, propagation, custom exception