DEV Community

Deepikandas
Deepikandas

Posted on • Edited on

#28 - Exception Handling -Checked Exception - part2

*Checked Exception in Java *

  • A checked exception is an exception that is checked at compile time by the compiler to ensure it is either handled using try-catch or declared using throws.
  • If a method can cause a checked exception, Java forces you to handle it before the program runs.


Important concept

βœ” Even if the file path is correct
βœ” Even if the file exists
❌ Compiler still requires handling because it’s a checked exception


*Why compiler forces checked exceptions
*

πŸ‘‰ Because checked exceptions represent predictable runtime problems that are likely to happen, so Java wants you to handle them before the program runs.
Predictable problems

Checked exceptions usually come from situations like:

file may not exist (IOException)
database may fail (SQLException)
class may not load (ClassNotFoundException)
Call Stack Behavior in Java Exception Handling


In Java, when an exception occurs (like ArrayIndexOutOfBoundsException), the method where the error happens immediately stops execution. If that method does not handle the exception using try-catch, the exception is passed upward through the call stack.

The call stack is the chain of method calls (e.g., printArray β†’ main β†’ JVM). Each level is checked for a matching catch block. If printArray() does not handle the exception, it is passed to main(), where it may be caught. If no method handles it, the JVM terminates the program and prints a stack trace.

This upward movement of the exception from one method to another is called stack unwinding or propagation up the call stack.

Top comments (0)