Exceptions(Java)

date
Jan 8, 2024
slug
java-exception
status
Published
tags
EXCEPTIONS
summary
type
Post
What are Exceptions ?
Exceptions in Java are like the alarm clocks of programming: nobody likes them, but they're necessary to keep things from spiralling into chaos. At their core, exceptions represent unexpected conditions or errors that occur during the execution of a program. They disrupt the normal flow of the application and, if not handled properly, can lead to program termination.
 
notion image
 
Types of Exceptions
In Java, exceptions are categorized into two main types:
  1. Checked exceptions
  1. Unchecked exceptions
Checked exceptions are those that the compiler requires you to handle explicitly, either by using a try-catch block or by declaring the exception with a throws clause in the method signature. These are often the "responsible" exceptions, like file not found or database connection issues, that you know might occur and need to be prepared for.
It can be created by extending Exception class
On the other hand, unchecked exceptions, also known as runtime exceptions, don't require explicit handling. These are the renegades of the exception world; they can strike anytime, anywhere, without warning. Examples include NullPointerException or ArrayIndexOutOfBoundsException. You might think you're safe, but boom! Your program crashes, and you're left scratching your head.
 
It can be create by extending RuntimeException class
 
 
Important Points to Remember from Effective Java(Joshua Bloch)
  1. A class with a “state-dependent” method that can be invoked only under certain unpredictable conditions should generally have a separate “state-testing” method indicating whether it is appropriate to invoke the state-dependent method. For example, the Iterator interface has the state-dependent method next and the corresponding state-testing method hasNext. This enables the standard idiom for iterating over a collection with a traditional for loop (as well as the for-each loop, where the hasNext method is used internally).
  1. An alternative to providing a separate state-testing method is to have the state-dependent method return an empty optional or a distinguished value such as null if it cannot perform the desired computation.
  1. Exceptions are designed for exceptional conditions. Don’t use them for ordinary control flow, and don’t write APIs that force others to do so.”
  1. If an object is to be accessed concurrently without external synchronization or is subject to externally induced state transitions, you must use an optional or distinguished return value, as the object’s state could change in the interval between the invocation of a state-testing method and its state-dependent method.
 

© Rupesh Dang 2021 - 2025