What’s difference: checked vs unchecked exceptions?

sakshisukla

Member
In Java, exceptions are events that disrupt the normal flow of a program. These exceptions are categorized mainly into two types: checked and unchecked.


Checked Exceptions:​


Checked exceptions are exceptions that are checked at compile-time. This means the compiler ensures that the method handles them using a try-catch block or declares them with a throws clause. If not handled, the code won’t compile. Common examples include IOException, SQLException, and ParseException.


Checked exceptions are typically used when the program should be aware of and handle potential failures, such as reading a file that might not exist or accessing a network resource that may be unavailable.

public void readFile(String path) throws IOException {
FileReader reader = new FileReader(path);
}


Unchecked Exceptions:​


Unchecked exceptions are not checked at compile-time, meaning the compiler doesn’t require you to handle them. These are subclasses of RuntimeException and include exceptions like NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.


These usually indicate programming errors such as logic bugs or improper use of an API. For example, trying to divide a number by zero or accessing an element outside of an array’s bounds.

int result = 10 / 0; // ArithmeticException


Key Differences:​


  • Compile-time checking: Checked exceptions must be either caught or declared; unchecked exceptions don’t require this.
  • Hierarchy: Checked exceptions are direct subclasses of Exception (excluding RuntimeException), while unchecked are subclasses of RuntimeException.
  • Use case: Checked for recoverable issues; unchecked for programming mistakes.

Understanding exception handling is crucial for writing robust Java applications, especially in real-world enterprise scenarios. If you're aiming to master this and build scalable applications, consider enrolling in a Java full stack developer course that covers these concepts in-depth.
 
Back
Top