0% found this document useful (0 votes)
6 views13 pages

Java Exceptions Lecture

The document is a lecture outline on Exception Handling in Java, covering topics such as exception definitions, hierarchy, try/catch/finally syntax, checked vs unchecked exceptions, and custom exceptions. It also discusses best practices for error handling and introduces advanced concepts like multi-catch and try-with-resources. Practice exercises are provided to reinforce the concepts learned in the lecture.

Uploaded by

abdoullahaljersi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views13 pages

Java Exceptions Lecture

The document is a lecture outline on Exception Handling in Java, covering topics such as exception definitions, hierarchy, try/catch/finally syntax, checked vs unchecked exceptions, and custom exceptions. It also discusses best practices for error handling and introduces advanced concepts like multi-catch and try-with-resources. Practice exercises are provided to reinforce the concepts learned in the lecture.

Uploaded by

abdoullahaljersi
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd

JAVA

Exceptions
Error Handling · try/catch/finally · Custom Exceptions · Best Practices
!
Instructor: Abdoullah Ndao

Java Programming — Exception Handling Lecture

Module 5 — Exception Handling & Error Management


Lecture Outline

01 What is an Exception? 05 throw & throws

02 Exception Hierarchy 06 Custom Exceptions

03 try / catch / finally 07 Multi-catch & try-with-resources

04 Checked vs Unchecked 08 Best Practices

Abdoullah Ndao · Java · Exceptions


What is an Exception?

Definition
📂 FileNotFoundException

An exception is an event that disrupts the normal flow of a


program. File you're trying to read doesn't exist on disk.

In Java, exceptions are objects that represent an error or


unexpected condition.

When a method cannot handle a situation, it throws an ➗ ArithmeticException


exception. The caller can then catch and handle it.

Without exceptions, programs would crash unpredictably and Division by zero: int x = 10 / 0;
bugs would be nearly impossible to trace.

🔗 NullPointerException

Calling a method on a null object reference.

Abdoullah Ndao · Java · Exceptions


Exception Hierarchy in Java

Throwable

Error Exception
Error — JVM fatal, never catch

JVM-level (never catch!) Recoverable conditions


Checked — must handle at compile time
OutOfMemoryError
StackOverflowError
RuntimeException — unchecked
Checked RuntimeException

IOException NullPointerException
SQLException ArithmeticException

Abdoullah Ndao · Java · Exceptions


try / catch / finally
Basic Syntax
try { }
try {
// Code that might throw
int result = 10 / 0; Wraps code that might throw. If exception occurs,
String str = null; control jumps immediately to the matching catch
[Link](); // NullPointerException block.
} catch (ArithmeticException e) {
[Link]("Math: " + [Link]());

} catch (NullPointerException e) {
[Link]("Null: " + [Link]());
catch (Type e) { }

} finally {
// ALWAYS runs — put cleanup here Handles a specific exception. Multiple catch blocks
[Link]("Done!"); can each handle a different exception type.
}

finally { }

Always executes, even without an exception. Use


Flow: try starts → exception thrown → matching catch runs → finally always runs → program continuesfor cleanup: close files, connections, and streams.
normally.

Abdoullah Ndao · Java · Exceptions


Checked vs Unchecked Exceptions

CHECKED UNCHECKED

Must handle at compile time—compiler enforces it No compile-time enforcement—discovered at runtime

• Extends Exception (not RuntimeException) • Extends RuntimeException


• Compiler ERROR if not caught or declared • Compiler does NOT force handling
• Represents recoverable conditions • Usually bugs in your code logic
• Use try-catch OR throws keyword • Fix root cause instead of catching

Example — Checked Example — Unchecked

// Compiler forces you to handle this // No compiler warning at all


public void readFile(String path) public void divide(int a, int b) {
throws IOException { int result = a / b;
FileReader fr = new FileReader(path); // Throws ArithmeticException
// ... must handle IOException // at runtime if b == 0 !
// or declare it with 'throws' }
}

Abdoullah Ndao · Java · Exceptions


throw & throws

throw throws
Used INSIDE a method to actually throw an exception object. Creates Used in a METHOD SIGNATURE to declare that a method may throw
and raises the exception right at that point. certain checked exceptions to its caller.

Using throw Using throws

public void setAge(int age) { // Declares it may throw IOException


if (age < 0 || age > 150) { public String readFile(String path)
// throw creates & raises it throws IOException {
throw new IllegalArgumentException(
"Invalid age: " + age FileReader fr = new FileReader(path);
); BufferedReader br = new BufferedReader(fr);
} return [Link]();
[Link] = age; // caller must handle the exception
} }

Abdoullah Ndao · Java · Exceptions


Custom Exceptions

1. Custom Checked Exception 2. Custom Unchecked Exception

public class InsufficientFundsException // Unchecked: extends RuntimeException


extends Exception { public class InvalidAgeException
private double amount; extends RuntimeException {

public InsufficientFundsException(double amt){ public InvalidAgeException(String msg) {


super("Insufficient funds: " + amt); super(msg);
[Link] = amt; }
} public InvalidAgeException(String msg,
public double getAmount(){ return amount; } Throwable cause) {
} super(msg, cause);
}
}

3. Use Your Custom Exception

public void withdraw(double amount) throws InsufficientFundsException {


if (amount > balance) {
throw new InsufficientFundsException(amount); // your custom exception
}
balance -= amount;
}

// Caller:
try { [Link](500); } catch (InsufficientFundsException e) { [Link]([Link]()); }

Abdoullah Ndao · Java · Exceptions


Multi-catch & try-with-resources (Java 7+)

Multi-catch (Java 7+) try-with-resources (Java 7+)

// Handle multiple types in one block // Resource auto-closed after block


try { try (FileReader fr = new FileReader("[Link]");
int[] arr = new int[5]; BufferedReader br = new BufferedReader(fr)) {
arr[10] = 1; // AIOOBE
int x = 10 / 0; // ArithmeticException String line = [Link]();
[Link](line);
} catch (ArrayIndexOutOfBoundsException |
ArithmeticException e) { } catch (IOException e) {
// handles both types! [Link]();
[Link]("Error: " + e); } // fr & br auto-closed here!
}

🚀 Multi-catch ♻️ try-with-resources 🔒 AutoCloseable

Reduces duplicate catch blocks. One handler for Auto calls close(). Prevents resource leaks. No Any class implementing AutoCloseable works:
multiple exception types. finally needed. InputStream, Connection, Scanner.

Abdoullah Ndao · Java · Exceptions


Best Practices

DO DON'T

Catch the most specific exception first catch (Exception e) {} — empty catch blocks

Always log or re-throw — never swallow silently Use exceptions for normal control flow

Use finally or try-with-resources for cleanup Catch Throwable or Error classes

Create meaningful custom exceptions Expose implementation details in messages

Chain exceptions to preserve the root cause Throw generic Exception — be specific

✨ Golden Rule: Throw early, catch late. Validate input at the top; handle exceptions at the layer that knows how to recover.

Abdoullah Ndao · Java · Exceptions


Practice Exercises

Beginner
Write divide(int a, int b) that catches ArithmeticException and returns 0 when
01 b is zero.
Safe Division

Intermediate
Read a text file line by line. Handle IOException in catch. Close BufferedReader
02 in finally.
File Reader

Intermediate
Create InsufficientFundsException. Implement withdraw() that throws it.
03 Catch in Main with a message.
BankAccount

Advanced
Build a layered app: DAO throws SQLException, Service wraps it in
04 ServiceException. Main shows both messages.
Exception Chaining

Abdoullah Ndao · Java · Exceptions


Cheat Sheet — Quick Reference

Essential Syntax Exception Type When

// try-catch-finally
try { ... } NullPointerException Unchecked null object reference
catch (SpecificException e) { ... }
catch (OtherException e) { ... } ArrayIndexOutOfBounds Unchecked invalid array index
finally { ... }

// Multi-catch (Java 7+) ArithmeticException Unchecked divide by zero


catch (IOException | SQLException e) { }
ClassCastException Unchecked bad type cast
// try-with-resources
try (Resource r = new Resource()) { }
IOException Checked I/O failure
// throw & throws
throw new MyException("msg");
public void m() throws IOException { } SQLException Checked database error

IllegalArgumentException Unchecked bad method argument

Checked Unchecked finally try-with

Compile-time enforced Runtime, not enforced Always runs Auto close resources
extends Exception extends RuntimeException Use for cleanup AutoCloseable

Abdoullah Ndao · Java · Exceptions


K e y Ta k e a w a y s

Exceptions in Java !
Exceptions represent disruptions in normal program flow

Hierarchy: Throwable → Error | Exception → RuntimeException

Checked = compile-time enforced · Unchecked = runtime

throw raises · throws declares · catch handles

Custom exceptions make error handling domain-specific

Best practice: throw early, catch late, never swallow

Abdoullah Ndao · Java Programming · Exception Handling

You might also like