Senior
What is the difference between checked and unchecked exceptions? When should RuntimeException be used?
sobes.tech AI
Answer from AI
In Java, exceptions are divided into checked and unchecked.
Checked exceptions are exceptions that are checked by the compiler. A method that can throw them must declare this with throws, and the calling code must handle them either through try-catch or by propagating further. Examples: IOException, SQLException.
Unchecked exceptions are descendants of RuntimeException and Error. The compiler does not require their mandatory handling or declaration. Usually, these are programming errors, such as NullPointerException, IllegalArgumentException.
When to use RuntimeException?
- If an error occurs due to incorrect API usage (for example, passing an invalid argument).
- If the error is unrecoverable and should not require explicit handling by the user.
- For errors resulting from logical mistakes in the code.
Example:
public void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException("Age cannot be negative");
}
this.age = age;
}