Exception Handling in Java
Chapter 9: Exception Handling in Java
In Java, exception handling is a powerful mechanism to handle runtime errors, allowing the normal flow of the program to continue. Without proper exception handling, errors can lead to unexpected termination of the program.
๐ What is an Exception?
An exception is an event that disrupts the normal flow of a program’s execution. It is an object which is thrown at runtime.
Common Exception Types:
- ArithmeticException – Divide by zero
- NullPointerException – Accessing object with null reference
- ArrayIndexOutOfBoundsException – Invalid index access
- NumberFormatException – Invalid number parsing
๐งช Java Exception Hierarchy
All exceptions are subclasses of Throwable
:
Throwable
Error
Exception
RuntimeException
๐ง Java Exception Handling Keywords
- try – Code that might throw an exception
- catch – Code to handle the exception
- finally – Code that executes regardless of an exception
- throw – Used to explicitly throw an exception
- throws – Declares the exceptions a method might throw
๐ก Example: try-catch
public class Demo {
public static void main(String[] args) {
try {
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Error: " + e.getMessage());
}
}
}
๐งน finally Block
The finally
block executes whether an exception is handled or not. It is often used to close resources like files or database connections.
Example:
try {
int data = 50 / 0;
} catch (ArithmeticException e) {
System.out.println("Exception caught");
} finally {
System.out.println("finally block is always executed");
}
๐ฏ throw Keyword
The throw
keyword is used to throw an exception explicitly.
throw new ArithmeticException("Divide by zero not allowed");
๐งพ throws Keyword
throws
is used to declare exceptions in the method signature.
public void readFile() throws IOException {
// file operations
}
๐งฐ Creating Custom Exceptions
We can create our own exception by extending Exception
class:
class MyException extends Exception {
MyException(String msg) {
super(msg);
}
}
✅ Benefits of Exception Handling
- Improves code robustness
- Enhances program readability
- Prevents abrupt termination
- Helps debugging and maintenance
๐ Chapter Summary
Concept | Description |
---|---|
Exception | Runtime error that disrupts program flow |
try-catch | Handle exceptions gracefully |
finally | Cleanup block executed always |
throw | Used to throw custom exception |
throws | Declares exceptions in method |
❓ FAQs with Answers
Q1: What is an exception in Java?
A: An exception is a runtime error that disrupts the normal flow of a program.
Q2: What are checked and unchecked exceptions?
A: Checked exceptions are checked at compile time (e.g., IOException). Unchecked exceptions occur at runtime (e.g., NullPointerException).
Q3: What is the use of finally block?
A: To ensure execution of important cleanup code, even if an exception occurs.
Q4: What’s the difference between throw and throws?
A: throw
is used to throw an exception, throws
is used to declare possible exceptions.
Q5: Can a method have multiple catch blocks?
A: Yes, to handle different types of exceptions separately.
Q6: What is a custom exception?
A: A user-defined class extending Exception
to represent specific errors.
Q7: What happens if an exception is not caught?
A: Program terminates and displays the exception stack trace.
Q8: Can we have try block without catch?
A: Yes, only if a finally
block is present.
Q9: How to catch multiple exceptions in one block?
A: From Java 7 onward, use pipe symbol (|):
catch (IOException | SQLException e) {}
Q10: Is it good to catch Exception class directly?
A: No, it’s not recommended as it hides specific exception causes.
๐ Related Links: Complete Java Course
- Chapter 1: Introduction to Java
- Chapter 2: Java Environment Setup
- Chapter 3: Variables and Data Types
- Chapter 4: Operators in Java
- Chapter 5: Control Statements
- Chapter 6: Loops in Java
- Chapter 7: Arrays and Strings
- Chapter 8: Object-Oriented Programming (OOP)
- Chapter 9: Inheritance and Polymorphism
- Chapter 10: Exception Handling
- Chapter 11: Multithreading
- Chapter 12: File Handling in Java
- Chapter 13: Applets and GUI (AWT/Swing)
- Chapter 14: Java Project Ideas & Practice Questions
๐ Related Links: Complete Java Course
- Chapter 1: Introduction to Java
- Chapter 2: Java Environment Setup
- Chapter 3: Variables and Data Types
- Chapter 4: Operators in Java
- Chapter 5: Control Statements
- Chapter 6: Loops in Java
- Chapter 7: Arrays and Strings
- Chapter 8: Object-Oriented Programming (OOP)
- Chapter 9: Inheritance and Polymorphism
- Chapter 10: Exception Handling
- Chapter 11: Multithreading
- Chapter 12: File Handling in Java
- Chapter 13: Applets and GUI (AWT/Swing)
- Chapter 14: Java Project Ideas & Practice Questions
Comments
Post a Comment