πŸš€ Java Advanced
Estimated reading: 4 minutes 50 views

⚠️ Java Exceptions: A Complete Guide with Examples, Best Practices & FAQs


🧲 Introduction – Why Java Exceptions Matter

Imagine your banking app suddenly crashes because of a division by zero. Or your file uploader stops working because a file wasn’t found. These are runtime errors β€” and Java Exception Handling is how we gracefully manage them.

Java’s exception handling mechanism ensures your programs are robust, fault-tolerant, and easy to debug by separating error-handling logic from normal logic.

βœ… By the end of this guide, you will:

  • Understand the types of exceptions in Java
  • Learn how to use try, catch, finally, and throw
  • Implement custom exceptions
  • Master best practices to write cleaner and safer Java code

πŸ”‘ What is an Exception in Java?

In Java, an exception is an event that disrupts the normal flow of a program. It is an object that is thrown at runtime when an abnormal condition occurs.

πŸ“˜ All exceptions are subclasses of Throwable, which has two major branches:

  • Exception – for conditions that a program might want to catch
  • Error – serious problems the application should not try to handle (like OutOfMemoryError)

🧱 Java Exception Hierarchy

Object  
  └── Throwable  
       β”œβ”€β”€ Exception  
       β”‚    β”œβ”€β”€ IOException  
       β”‚    β”œβ”€β”€ SQLException  
       β”‚    └── RuntimeException  
       β”‚         β”œβ”€β”€ ArithmeticException  
       β”‚         β”œβ”€β”€ NullPointerException  
       β”‚         └── IndexOutOfBoundsException  
       └── Error  
            └── StackOverflowError, etc.

πŸ“Œ Types of Exceptions in Java

TypeDescriptionExamples
Checked ExceptionMust be caught or declared using throwsIOException, SQLException
Unchecked ExceptionOccurs at runtime, not checked by compilerNullPointerException, ArithmeticException
ErrorsSerious problems, usually not handled in codeOutOfMemoryError, StackOverflowError

πŸ› οΈ Handling Exceptions in Java

βœ… Basic Example using try-catch

public class ExceptionExample {
    public static void main(String[] args) {
        try {
            int result = 10 / 0; // Division by zero
        } catch (ArithmeticException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}

πŸ” Explanation:

  • try block holds code that might throw an exception
  • catch handles the specific exception
  • ArithmeticException is thrown, and caught here

🧼 Using finally Block

public class FinallyExample {
    public static void main(String[] args) {
        try {
            String name = null;
            System.out.println(name.length());
        } catch (NullPointerException e) {
            System.out.println("Caught: " + e.getMessage());
        } finally {
            System.out.println("Finally block always runs.");
        }
    }
}

βœ… finally block always executes β€” whether or not an exception is thrown.


πŸš€ Throwing Exceptions Manually using throw

public class ThrowExample {
    public static void validate(int age) {
        if (age < 18)
            throw new IllegalArgumentException("You must be 18+");
    }

    public static void main(String[] args) {
        validate(15);
    }
}

βœ… Use throw to manually trigger exceptions.


πŸ“€ Declaring Exceptions using throws

public class ThrowsExample {
    public static void readFile(String path) throws IOException {
        FileReader file = new FileReader(path);
    }
}

βœ… Use throws to propagate exceptions to the caller.


πŸ› οΈ Creating Custom Exceptions

class MyException extends Exception {
    public MyException(String message) {
        super(message);
    }
}

public class CustomExample {
    public static void check(int value) throws MyException {
        if (value < 100) {
            throw new MyException("Value too small!");
        }
    }

    public static void main(String[] args) {
        try {
            check(50);
        } catch (MyException e) {
            System.out.println("Custom Exception: " + e.getMessage());
        }
    }
}

πŸ“˜ You can create custom exceptions by extending the Exception class.


πŸ’‘ Best Practices for Exception Handling in Java

  • βœ… Catch specific exceptions β€” avoid using generic Exception
  • βœ… Log exceptions with meaningful messages
  • βœ… Avoid swallowing exceptions silently (e.g., empty catch block)
  • βœ… Never use exceptions for flow control
  • βœ… Use custom exceptions for domain-specific rules

πŸ“Š Comparison Table – throw vs throws

Featurethrowthrows
PurposeTo throw an exception manuallyTo declare exception that can be thrown
Used InMethod bodyMethod signature
Follows ByException instanceException class name
Examplethrow new IOException();throws IOException

🧾 Summary

  • Java uses a powerful exception handling mechanism for robust applications.
  • Learn to catch, throw, declare, and even create custom exceptions.
  • Follow best practices to maintain readability, safety, and maintainability in your code.

❓ FAQ Section

❓ What is the difference between checked and unchecked exceptions in Java?

Checked exceptions must be handled using try-catch or declared with throws. Unchecked exceptions occur at runtime and are not checked by the compiler.


❓ Can we catch multiple exceptions in one block?

Yes, using multi-catch syntax:

try {
    // risky code
} catch (IOException | SQLException ex) {
    System.out.println("Handled: " + ex);
}

❓ What if we don’t handle a checked exception?

The program won’t compile unless it is handled or declared using throws.


❓ Can a finally block be skipped?

Only if the JVM exits forcibly (e.g., System.exit()), otherwise it always executes.


❓ Is it good practice to catch Exception or Throwable?

⚠️ No. Catch the most specific exceptions possible to maintain clean, predictable code.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

Java Exceptions

Or Copy Link

CONTENTS
Scroll to Top