Exceptions in Java are events that occur during the execution of a program that disrupt the normal flow of instructions. They are objects that represent error conditions or unexpected behavior in a program.
try-catch
block or declared in the method signature using the throws
keyword.IOException
, SQLException
.RuntimeException
.NullPointerException
, ArrayIndexOutOfBoundsException
.OutOfMemoryError
, StackOverflowError
.Java provides a robust mechanism to handle exceptions through the use of try
, catch
, finally
, and throw
keywords.
try: Code that might throw an exception is placed inside a try
block.
catch: Code to handle the exception is placed inside a catch
block.
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
}
Multiple catch
blocks can be used to handle different types of exceptions.
try {
// Code that may throw multiple exceptions
} catch (IOException e) {
// Handle IOException
} catch (SQLException e) {
// Handle SQLException
}
A finally
block contains code that is always executed, whether an exception is thrown or not. It is typically used for resource cleanup.
try {
// Code that may throw an exception
} catch (ExceptionType e) {
// Code to handle the exception
} finally {
// Code to execute regardless of an exception
}
The throw
keyword is used to explicitly throw an exception.
public void myMethod() throws IOException {
throw new IOException("Exception message");
}
The throws
keyword is used in a method signature to declare that the method can throw specified exceptions.
public void myMethod() throws IOException, SQLException {
// Method code
}
import java.io.*;
public class ExceptionExample {
public static void main(String[] args) {
try {
FileReader file = new FileReader("test.txt");
BufferedReader fileInput = new BufferedReader(file);
// Reading first line of file
System.out.println(fileInput.readLine());
fileInput.close();
} catch (FileNotFoundException e) {
System.out.println("File not found");
} catch (IOException e) {
System.out.println("Error reading file");
} finally {
System.out.println("Execution finished");
}
}
}
try
, catch
, finally
, throw
, throws
.More Information about Exceptions, Exception Handling and Errors: https://codevisionz.com/courses/java-errors-exception-handling/