Exceptions in java ( AI article)
In Java, exceptions are events that disrupt the normal flow of a program's execution. They are used to handle errors and other exceptional events in a controlled manner. When an exception occurs, Java creates an exception object and "throws" it. The exception can then be "caught" and processed using special code blocks.
Key Concepts of Exceptions in Java:
1. Types of Exceptions:
Checked Exceptions: These are exceptions that are checked at compile-time. The programmer must handle these exceptions using a try-catch block or declare them using the throws keyword.
Example: IOException, SQLException.
Unchecked Exceptions: These exceptions are not checked at compile-time and occur due to programming errors. They extend RuntimeException and do not need to be explicitly handled.
Example: NullPointerException, ArrayIndexOutOfBoundsException.
Errors: These are serious problems, usually related to system resources, and should not be handled by normal exception-handling code.
Example: StackOverflowError, OutOfMemoryError.
2. Hierarchy of Exception Classes:
Throwable: This is the root class for all errors and exceptions.
Exception: All exceptions are derived from this class.
RuntimeException: Unchecked exceptions.
Other checked exceptions: Like IOException, SQLException.
Error: Serious issues like OutOfMemoryError, StackOverflowError.
3. Basic Structure of Exception Handling:
try: Block of code that may throw an exception.
catch: Block of code to handle the exception.
finally: Block of code that always executes after the try/catch, whether an exception occurs or not.
throw: Keyword used to explicitly throw an exception.
throws: Used in method signatures to declare that a method might throw exceptions.
Example: Handling Exceptions with try-catch
public class ExceptionExample {
public static void main(String[] args) {
try {
// Code that may throw an exception
int result = 10 / 0; // This will cause an ArithmeticException
System.out.println(result);
} catch (ArithmeticException e) {
// Handling the exception
System.out.println("Error: Division by zero is not allowed.");
} finally {
// This block always runs
System.out.println("This will always execute.");
}
}
}
Output:
Error: Division by zero is not allowed.
This will always execute.
4. Throwing an Exception:
You can use the throw keyword to explicitly throw an exception.
public class ThrowExample {
public static void checkAge(int age) {
if (age < 18) {
throw new ArithmeticException("Not eligible to vote");
} else {
System.out.println("Eligible to vote");
}
}
public static void main(String[] args) {
checkAge(16); // This will throw an exception
}
}
Output:
Exception in thread "main" java.lang.ArithmeticException: Not eligible to vote
5. Declaring Exceptions with throws:
The throws keyword is used in the method signature to declare that a method may throw certain exceptions.
import java.io.*;
public class ThrowsExample {
public static void readFile() throws IOException {
FileReader file = new FileReader("non_existent_file.txt");
BufferedReader fileInput = new BufferedReader(file);
// Print first line of the file
System.out.println(fileInput.readLine());
}
public static void main(String[] args) {
try {
readFile();
} catch (IOException e) {
System.out.println("An error occurred: " + e.getMessage());
}
}
}
Output:
An error occurred: non_existent_file.txt (No such file or directory)
6. finally Block:
The finally block always executes after the try-catch, regardless of whether an exception occurred or not. It is often used to close resources like files or database connections.
public class FinallyExample {
public static void main(String[] args) {
try {
int data = 50 / 0;
} catch (ArithmeticException e) {
System.out.println("ArithmeticException caught");
} finally {
System.out.println("This block always runs");
}
}
}
Output:
ArithmeticException caught
This block always runs
7. Custom Exceptions:
You can create your own custom exceptions by extending the Exception class (or RuntimeException for unchecked exceptions).
class InvalidAgeException extends Exception {
public InvalidAgeException(String message) {
super(message);
}
}
public class CustomExceptionExample {
public static void checkAge(int age) throws InvalidAgeException {
if (age < 18) {
throw new InvalidAgeException("Age is not valid for voting.");
} else {
System.out.println("Eligible to vote.");
}
}
public static void main(String[] args) {
try {
checkAge(15);
} catch (InvalidAge
Comments
Post a Comment