An Exception in Java is a subclass of Throwable
that represents an abnormal condition during program execution — but one that the program can recover from.
For example:
null
objectExceptions are typically caused by programmer mistakes or external issues (e.g., bad input or unavailable resources).
An Error is also a subclass of Throwable
, but it represents serious problems that a program cannot recover from — typically related to the JVM or system-level issues.
For example:
Errors are typically not meant to be caught or handled in most cases.
Feature | Exception | Error |
---|---|---|
Definition | Represents a recoverable abnormal condition. | Represents serious, unrecoverable problems. |
Type | Checked (IOException ) or Unchecked (NullPointerException ). |
Unchecked only (StackOverflowError , OutOfMemoryError ). |
Caused by | Programmer mistakes or external factors. | System-level or JVM issues. |
Handling | Meant to be caught and handled. | Rarely handled (let the JVM deal with it). |
Recovery | Recovery is possible (e.g., retry, fallback). | Recovery is typically impossible. |
Examples | IOException , NullPointerException , ArithmeticException . |
OutOfMemoryError , StackOverflowError , VirtualMachineError . |
1 | Throwable |
Checked exceptions are designed for situations you should anticipate and recover from. The compiler forces you to handle them, ensuring your program deals with expected issues gracefully (e.g., file not found, network issues).
Key Characteristics:
Exception
(but not from RuntimeException
).try-catch
or throws
.Common Checked Exceptions:
Exception Name | When it happens |
---|---|
IOException |
Input-output operations fail (e.g., file not found). |
SQLException |
Database access errors. |
FileNotFoundException |
File cannot be found. |
ClassNotFoundException |
Class loading fails (e.g., reflection). |
ParseException |
Failure in parsing data (e.g., date strings). |
InterruptedException |
Thread is interrupted while sleeping or waiting. |
Best Practices for Checked Exceptions:
✅ Use when recovery is possible (e.g., retry file loading, prompt user for correct file).
✅ Catch the most specific exceptions first (e.g., FileNotFoundException
before IOException
).
❌ Avoid catching Exception
directly unless you truly need a catch-all.
❌ Don’t overuse them — too many checked exceptions make code hard to read.
Unchecked exceptions indicate programming logic errors that shouldn’t happen if the code is correct. The compiler doesn’t force you to handle these — but you can catch them if needed.
Key Characteristics:
RuntimeException
.Common Unchecked Exceptions:
Exception Name | When it happens |
---|---|
NullPointerException |
Trying to access a method/field on a null object. |
ArrayIndexOutOfBoundsException |
Array index is invalid (e.g., arr[5] when size is 4). |
ArithmeticException |
Divide by zero (int result = 10 / 0 ). |
IllegalArgumentException |
Method receives an invalid argument (e.g., negative age). |
ClassCastException |
Wrong type casting (e.g., (String) obj when obj is Integer). |
NumberFormatException |
Parsing a non-numeric string to a number (Integer.parseInt("abc") ). |
Best Practices for Unchecked Exceptions:
if (str != null)
checks).IllegalArgumentException
and IllegalStateException
for custom validations.These keywords handle exceptions directly — catching and managing errors when they happen.
try
— Wraps code that may throw an exception.try
block is executed, but if any exception occurs, it will jump to the corresponding catch
block.catch
— Catches and handles a specific exception.catch
block handles one specific type of exception.catch
blocks for different exceptions, but order matters (catch more specific exceptions first).catch
block as an argument (e.g., Exception e
), which you can use to retrieve information about the exception (e.g., e.getMessage()
).catch (Exception1 | Exception2 | Exception3)
finally
— Runs code after try
and catch
— always executes (good for cleanup).try
and catch
blocks, making sure critical resources are freed, even if the program crashes.return
statement is inside try
or catch
, the finally
block still executes before the method returns.finally
, it overrides any exception from the try
block.1 | try { |
These keywords are used to trigger exceptions manually or declare that a method might throw exceptions.
throw
Purpose: Manually throws an exception at a specific point in your code.
throw new SomeException("Message");
1 | if (age < 18) { |
throws
Purpose: Declares that a method may throw one or more exceptions.
throws
in the method signature.1 | public void readFile() throws IOException, FileNotFoundException { |
You can define your own exceptions to represent specific errors in your application.
Exception
Purpose: The base class for checked exceptions.
throws
.Exception
to create custom checked exceptions.1 | public class InvalidInputException extends Exception { |
RuntimeException
Purpose: The base class for unchecked exceptions.
1 | public class InvalidAgeException extends RuntimeException { |
Throwable
Purpose: The superclass for both Exception
and Error
.
Exception
or RuntimeException
.OutOfMemoryError
).1 | try { |