Exception Handling in Java
Exception Handling in Java
Exception Handling in Java is a mechanism that allows you to handle runtime errors, ensuring the normal flow of the application. It helps catch unexpected conditions and define how the program should respond.
✅ Key Concepts
1. What is an Exception?
An exception is an event that disrupts the normal flow of a program's instructions.
2. Types of Exceptions
Type Description
Checked Must be handled or declared (e.g., IOException)
Unchecked Runtime exceptions (e.g., NullPointerException)
Errors Serious problems (e.g., OutOfMemoryError)
๐ง Basic Syntax
try-catch Block
java
Copy
Edit
try {
// Code that might throw an exception
int result = 10 / 0;
} catch (ArithmeticException e) {
System.out.println("Cannot divide by zero!");
}
try-catch-finally
java
Copy
Edit
try {
int[] arr = new int[2];
arr[5] = 10; // This will throw ArrayIndexOutOfBoundsException
} catch (ArrayIndexOutOfBoundsException e) {
System.out.println("Index out of bounds!");
} finally {
System.out.println("This block always runs.");
}
throws Keyword
Used to declare exceptions that a method might throw.
java
Copy
Edit
public void readFile(String file) throws IOException {
FileReader fr = new FileReader(file);
}
๐ ️ Custom Exception Example
You can create your own exceptions by extending Exception or RuntimeException.
java
Copy
Edit
class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
public class Test {
public static void main(String[] args) {
try {
throw new MyException("Custom error occurred!");
} catch (MyException e) {
System.out.println(e.getMessage());
}
}
}
๐ง Best Practices
Catch specific exceptions first, not generic Exception.
Avoid empty catch blocks.
Use finally for cleanup (e.g., closing files, releasing resources).
Don’t use exceptions for flow control.
Log exceptions properly with a logging framework (e.g., SLF4J, Log4j).
๐ Summary
Keyword Description
try Wrap code that might throw exceptions
catch Handle specific exception types
finally Always runs; used for cleanup
throw Throw an exception manually
throws Declare an exception that a method may throw
Learn Full Stack JAVA Course in Hyderabad
Read More
Java Collections Framework: List, Set, Map
Java Data Types and Variables Explained
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment