What are checked Exceptions in Java?
Checked exceptions in Java are exceptions that you must explicitly handle or declare. These exceptions are subclasses of the Throwable
class, excluding Error
, RuntimeException
, and their subclasses.
The key characteristics of checked exceptions
The key characteristics of checked exceptions are:
Explicit Handling: You must either catch checked exceptions using a try-catch block or declare them in the method signature using the throws keyword. If you fail to do either, your code will not compile, resulting in a compilation error.
Checked by the Compiler: The Java compiler enforces the handling or declaration of checked exceptions. This ensures that we are aware of the exceptional conditions that may arise and are prompted to handle them appropriately.
Examples of Checked Exceptions include
Examples of checked exceptions include:
- IOException: You encounter this when an input-output operation fails or is interrupted.
- SQLException: This exception is raised for errors that occur while working with databases using SQL.
- FileNotFoundException: You see this when trying to access a file that does not exist.
- InvocationTargetException: This exception wraps an exception thrown by a method invoked through reflection.
- CloneNotSupportedException: You get this when trying to clone an object that does not implement the
Cloneable
interface. - ClassNotFoundException: This is raised when trying to load a class that does not exist.
- InstantiationException: You encounter this when trying to create an instance of an abstract class or an interface.
These checked exceptions help ensure that exceptional situations are handled explicitly, making our Java code more robust and reliable. By requiring us to handle or declare checked exceptions, Java promotes better error handling and increases the reliability of our software systems.