15. Java Exception
T
Tuan Nguyen

15. Java Exception

This section focuses on Java exception handling concepts including checked and unchecked exceptions, try-catch-finally, custom exceptions, transaction rollback behavior, resource management, and best practices for building reliable enterprise backend applications.

1. What is exception?

An exception is an event that interrupts normal program execution.

Exceptions usually represent abnormal situations such as:

Invalid input
Database failure
Network issue
File not found
Null access

Example:

int x = 10 / 0;

This throws:

ArithmeticException

Exceptions allow applications to detect and handle problems gracefully instead of crashing unexpectedly.


2. Difference between exception and error?

This is a common interview question.


Exception

Exceptions represent problems applications can potentially handle.

Examples:

IOException
SQLException
IllegalArgumentException

Applications are expected to recover or respond properly.


Error

Errors represent serious JVM or system-level failures.

Examples:

OutOfMemoryError
StackOverflowError
VirtualMachineError

Errors are usually not recoverable.


Main difference:

Exception

Error

Recoverable

Usually unrecoverable

Application-level issue

JVM/system-level issue

Can often be handled

Usually should not be handled


3. What is checked exception?

Checked exceptions are verified at compile time.

Java forces developers to:

Handle exception
or
Declare exception

Examples:

IOException
SQLException
FileNotFoundException

Example:

public void read() throws IOException {
}

Checked exceptions represent expected recoverable situations.


4. What is unchecked exception?

Unchecked exceptions occur at runtime.

Compiler does not force explicit handling.

Examples:

NullPointerException
IllegalArgumentException
IllegalStateException

Unchecked exceptions usually indicate programming bugs or invalid application state.


5. What is RuntimeException?

RuntimeException is the base class for unchecked exceptions.

Examples:

NullPointerException
IllegalArgumentException
IllegalStateException
IndexOutOfBoundsException

Runtime exceptions are not required to be declared using throws.

Spring heavily uses unchecked exceptions.


6. What is NullPointerException?

NullPointerException occurs when code tries to access a null reference.

Example:

String s = null;
s.length();

Common causes:

Uninitialized variables
Missing dependency injection
Null database values
Incorrect assumptions

Very common Java runtime exception.


7. What is IllegalArgumentException?

IllegalArgumentException means a method received invalid input parameters.

Example:

public void setAge(int age) {

    if (age < 0) {
        throw new IllegalArgumentException("Invalid age");
    }
}

Used for validation failures.


8. What is IllegalStateException?

IllegalStateException means the object state is invalid for the requested operation.

Example:

if (!isConnected) {
    throw new IllegalStateException("Connection not established");
}

Difference:

Exception

Meaning

IllegalArgumentException

Invalid input

IllegalStateException

Invalid object state


9. What is IOException?

IOException represents input/output failures.

Examples:

File read failure
Network communication issue
Stream failure

Example:

Files.readString(path);

may throw IOException.

It is a checked exception.


10. What is SQLException?

SQLException represents database access failures.

Examples:

Connection failure
Invalid SQL
Constraint violation
Transaction failure

It is also a checked exception.

In Spring applications, SQLException is often translated into unchecked DataAccessException.


11. What is try-catch?

try-catch handles exceptions safely.

Example:

try {
    int x = 10 / 0;
} catch (ArithmeticException e) {
    System.out.println("Error");
}

Flow:

try block executes
→ exception occurs
→ matching catch block handles exception

Without handling, exception propagates upward.


12. What is finally?

finally contains code that executes after try/catch.

Example:

try {
} finally {
    System.out.println("Cleanup");
}

Usually used for:

Resource cleanup
Connection closing
File closing
Logging

13. Does finally always execute?

Usually yes.

Even if exception occurs:

try {
    throw new RuntimeException();
} finally {
    System.out.println("Finally");
}

finally still executes.

However, there are rare exceptions:

System.exit()
JVM crash
Power failure
Fatal system error

14. What is throw?

throw explicitly throws an exception.

Example:

throw new IllegalArgumentException("Invalid input");

Used inside method body.


15. What is throws?

throws declares possible exceptions in method signature.

Example:

public void readFile() throws IOException {
}

It informs callers that the method may throw exception.


16. Difference between throw and throws?

throw

throws

Actually throws exception

Declares possible exception

Used inside method

Used in method signature

Example:

throw new RuntimeException();

Example:

void test() throws IOException

17. What is custom exception?

Custom exception is an application-specific exception class.

Example:

public class UserNotFoundException
        extends RuntimeException {

    public UserNotFoundException(String message) {
        super(message);
    }
}

Useful for:

Business errors
Domain-specific problems
Cleaner error handling
Better API responses

Custom exceptions improve readability and maintainability.


18. What is stack trace?

Stack trace shows method call hierarchy leading to exception.

Example:

Exception in thread "main"
java.lang.NullPointerException
    at UserService.find(UserService.java:20)
    at Main.main(Main.java:10)

It helps developers locate the failure source.

Stack traces are critical for debugging.


19. What is exception propagation?

Exception propagation means exceptions move upward through method calls until handled.

Example:

methodC throws exception
→ methodB
→ methodA
→ main

If nobody handles exception, JVM terminates thread/application.


20. Can we catch multiple exceptions?

Yes.

Example:

try {
} catch (IOException e) {
} catch (SQLException e) {
}

Different catch blocks handle different exception types.


21. What is multi-catch?

Multi-catch allows handling multiple exceptions in one catch block.

Example:

catch (IOException | SQLException e) {
}

Useful when handling logic is identical.

Introduced in Java 7.


22. What is try-with-resources?

try-with-resources automatically closes resources.

Example:

try (BufferedReader br =
        new BufferedReader(new FileReader("a.txt"))) {

}

Java automatically calls:

close()

even if exception occurs.


23. What is AutoCloseable?

AutoCloseable is an interface for resources that can be closed automatically.

Example:

public interface AutoCloseable {
    void close() throws Exception;
}

Resources used in try-with-resources must implement AutoCloseable.

Examples:

BufferedReader
Connection
InputStream

24. Why is try-with-resources useful?

Benefits:

Automatic cleanup
Avoids resource leaks
Cleaner code
Safer exception handling

Without it, developers may forget closing resources manually.


25. Should we catch Exception?

Usually avoid catching generic Exception unless truly necessary.

Bad example:

catch (Exception e) {
}

Problems:

Hides real issues
Too broad
Harder debugging
Swallows important exceptions

Prefer catching specific exceptions.


26. Should we catch Throwable?

Almost never.

Throwable includes:

Exception
Error

Catching Throwable may accidentally catch serious JVM errors like:

OutOfMemoryError
StackOverflowError

Applications usually should not attempt recovering from JVM-level failures.


27. What are best practices for exception handling?

Important best practices:

Practice

Reason

Catch specific exceptions

Better control

Avoid empty catch blocks

Prevent hidden bugs

Use custom exceptions

Better domain modeling

Log useful context

Easier debugging

Do not expose internal stack traces to users

Security

Use global exception handling

Centralized error management

Avoid exceptions for normal flow

Performance/readability

Good exception handling improves reliability and maintainability.


28. How do exceptions affect Spring transactions?

By default Spring rolls back transactions only for unchecked exceptions.

Rollback occurs for:

RuntimeException
Error

Example:

@Transactional
public void process() {
    throw new RuntimeException();
}

Transaction rolls back automatically.

But checked exceptions usually do NOT trigger rollback automatically.

Example:

@Transactional
public void process() throws IOException {
    throw new IOException();
}

Rollback may not happen unless configured:

@Transactional(rollbackFor = IOException.class)

29. Why are unchecked exceptions common in Spring?

Spring prefers unchecked exceptions because:

Cleaner method signatures
Less boilerplate
Better transaction rollback behavior
Simpler propagation

Checked exceptions force excessive:

throws declarations
try-catch blocks

Spring transaction management also works naturally with RuntimeException.


30. What is global exception handling?

Global exception handling centralizes API error handling.

Instead of handling exceptions in every controller:

try {
} catch (...) {
}

Spring provides:

@RestControllerAdvice

Example:

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(UserNotFoundException.class)
    public ResponseEntity<?> handle(
            UserNotFoundException ex) {

        return ResponseEntity
            .status(404)
            .body(ex.getMessage());
    }
}

Benefits:

Centralized error handling
Consistent API responses
Cleaner controllers
Better maintainability

Very common in enterprise Spring Boot applications.

Comments