CH11_Exception Handling
CS 321: Object Oriented Programming 2
Chapter 11: Exception Handling
Instructor: Mrs. Mona Altassan
Reference: Java™ How to Program, 10/e
Objectives of Chapter 11
Understand exceptions: What they are and their handling.
Usage of exception handling: Learn when and how to apply exception handling.
Try blocks: Learn to use try blocks to encapsulate code that may generate exceptions.
Throw keyword: Use
throwto indicate issues in the program.Catch blocks: Set up
catchblocks to define exception handlers for different exception types.Finally block: Understand how to use the
finallyblock to ensure resource release regardless of exception occurrence.Exception class hierarchy: Learn about the hierarchy of exceptions in Java.
User-defined exceptions: Create exceptions tailored for specific needs.
11.1 Introduction to Exception Handling
Definition: Exception refers to problems encountered during a program's execution.
Infrequent problems: The term 'exception' implies such issues are not common.
Robust applications: Exception handling enables programs to continue functioning instead of crashing upon encountering errors.
11.2 Examples of Exception Handling
Example 1: Divide by Zero
Without Exception Handling: Attempting to divide by zero leads to errors that terminate the program.
Stack Trace: Provides the exception name, descriptive message, and the method-call stack at the time of the exception, aiding in debugging.
ArithmeticException: Specifically thrown when division by zero occurs in integer arithmetic. Floating-point values handle division by zero differently, resulting in
Infinity.InputMismatchException: Occurs when non-integer input is provided where an integer is expected.
Example 2: Handling Exceptions
Utilizing
try-catchblocks to manage potential exceptions, allowing users to input new values upon errors rather than terminating the program:Syntax for
try-catch:try { // statements that may cause an exception } catch (ExceptionType e) { // error handling code }Multiple
catchblocks: You can define several catch clauses for different exception types.Multi-catch: Use of a single catch block to handle multiple exception types introduced in Java SE 7, e.g.,
catch (Type1 | Type2 e).
11.3 Overview of Exception Handling Structure
Catch Block Characteristics:
Must follow a
tryblock.Enables response actions for different exception types.
Flow after Exception: Control resumes after the
catchblocks once exception handling concludes.Scope of Local Variables: Local variables within the
tryblock are not accessible incatchblocks and cease to exist after the block terminates.
11.4 When to Use Exception Handling
Effective for handling synchronous errors such as:
Out-of-range array indices
Arithmetic overflow
Division by zero
Not typically used for asynchronous events such as I/O completions or user interactions.
11.5 Java Exception Hierarchy
Hierarchy Structure: Based on class
Throwable, which branches intoExceptionandErrorclasses.Custom Exceptions: Programmers can define their own exceptions by extending existing classes, allowing for tailored error definitions.
Differences in Exception Types:
Checked Exceptions: Must be caught or declared because they fall outside the control of the program (e.g., file operations).
Unchecked Exceptions: Include logic errors (e.g.,
ArithmeticException); the programmer is responsible for avoiding these errors.
11.6 Finally Block and Resource Management
Resource Management:
finallyensures resources are returns to the system, thereby preventing leaks.Execution Behavior:
Always Executes: Whether an exception is thrown or not within the
tryblock.Used for cleanup: Ensures files or connections are closed even when exceptions occur.
11.9 Declaring New Exception Types
Creating Custom Classes: Users can define new exceptions that extend existing ones to suit specific needs:
Should include constructors to pass error messages or other exception objects.
Example Syntax for Custom Exceptions:
public class MyOwnException extends Exception {
public MyOwnException() {
}
public MyOwnException(String message) {
super(message);
}
public MyOwnException(Throwable cause) {
super(cause);
}
public MyOwnException(String message, Throwable cause) {
super(message, cause);
}
}11.10 Preconditions and Postconditions
Preconditions: Conditions that must be true before a method executes.
Postconditions: Conditions that are ensured to be true after a method completes.
Documenting these helps clarify method responsibilities and debugging aids.
11.11 Assertions in Java
Usage Context: Assertions provide a means to verify assumptions about the program during execution.
Syntax for assertions in Java:
assert expression1 : expression2; // expression2 is the error messageEnable Assertions: By default, assertions are turned off; they can be enabled via command-line options.