Checked exceptions in Java are exceptions that are checked at compile time, which means you must either catch them using a try-catch block or declare that your method throws these exceptions using the throws keyword. Here are some common examples of checked exceptions in Java:
IOException: This exception is thrown when there is an error while reading from or writing to files or streams.
import java.io.*;
public class IOExceptionExample {
public static void main(String[] args) {
try {
FileReader reader = new FileReader("example.txt");
// Perform file operations here
} catch (IOException e) {
e.printStackTrace();
}
}
}
FileNotFoundException: Raised when an attempt to access a file that doesn't exist is made.
import java.io.*;
public class FileNotFoundExceptionExample {
public static void main(String[] args) {
try {
FileInputStream fileInputStream = new FileInputStream("nonexistent.txt");
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
ClassNotFoundException: This exception occurs when you try to load a class that doesn't exist.
public class ClassNotFoundExceptionExample {
public static void main(String[] args) {
try {
Class.forName("NonExistentClass");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
SQLException: This is an exception specific to database operations.
import java.sql.*;
public class SQLExceptionExample {
public static void main(String[] args) {
try {
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/nonexistentdb", "user", "password");
} catch (SQLException e) {
e.printStackTrace();
}
}
}
ParseException: Thrown when there is an error during parsing, commonly used with date and time parsing.
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class ParseExceptionExample {
public static void main(String[] args) {
try {
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date date = dateFormat.parse("invalid-date");
} catch (ParseException e) {
e.printStackTrace();
}
}
}
These examples demonstrate various checked exceptions in Java. Remember to handle these exceptions properly in your code to provide robust error handling and improve the reliability of your applications.