DEV Community

Cover image for Exception Handling in Java (Best Practices)
naveen kumar
naveen kumar

Posted on

Exception Handling in Java (Best Practices)

Exception Handling in Java: Stop Your Apps from Crashing Like a Beginner

Let’s be honest.

Every developer has written code that worked perfectly… until it didn’t.

  • A user enters wrong input.
  • A file is missing.
  • A server doesn’t respond.

And suddenly… your application crashes.

That’s not just a bug — that’s a bad user experience.

This is exactly where exception handling in Java saves you.

What is Exception Handling?

In simple terms, an exception is something that breaks your program’s normal flow.

Exception handling is how you deal with that break without crashing your app.

Instead of your program saying “I’m done”, it says:
** “Something went wrong… but I’ve got this.”**

** The Classic Crash Example**

int a = 10;
int b = 0;
System.out.println(a / b);
Enter fullscreen mode Exit fullscreen mode

Boom 💥
ArithmeticException

Your program stops instantly.

Now imagine this happening in a banking app or payment system

Why Exception Handling is a Must-Have Skill

✔ Your app doesn’t crash unexpectedly
✔ Users don’t get frustrated
✔ Debugging becomes easier
✔ Your code looks professional
✔ You handle real-world scenarios like a pro

Types of Exceptions (Quick Understanding)

** Checked Exceptions**

✔ Caught at compile-time
✔ Must be handled
✔ Example: IOException, SQLException

These usually come from external systems like files or databases.

Unchecked Exceptions

✔ Occur at runtime
✔ Not forced by compiler
✔ Example: NullPointerException, ArithmeticException

Mostly caused by developer mistakes.

** Core Keywords You Must Know**

✔ try → risky code goes here
✔ catch → handles the error
✔ finally → always runs
✔ throw → manually create exception
✔ throws → declare exception

Fixing the Crash (Basic Example)

try {
    int a = 10;
    int b = 0;
    System.out.println(a / b);
} catch (ArithmeticException e) {
    System.out.println("Cannot divide by zero");
}
Enter fullscreen mode Exit fullscreen mode

Now instead of crashing ❌
Your app handles it smoothly ✅

Handling Multiple Errors

try {
    int arr[] = new int[5];
    arr[10] = 50;
} catch (ArrayIndexOutOfBoundsException e) {
    System.out.println("Index error");
} catch (Exception e) {
    System.out.println("Something went wrong");
}
Enter fullscreen mode Exit fullscreen mode

✔ Different problems → different handling
✔ Cleaner and safer code

Why finally is Important

try {
    System.out.println("Running...");
} finally {
    System.out.println("Always executed");
}
Enter fullscreen mode Exit fullscreen mode

✔ Runs no matter what
✔ Used for cleanup (closing files, DB connections, etc.)

Throwing Exceptions Yourself

if(age < 18) {
    throw new ArithmeticException("Not eligible");
}

Enter fullscreen mode Exit fullscreen mode

✔ You control the rules
✔ Useful in validation logic

** Using throws**

void readFile() throws IOException {
    // file logic
}

Enter fullscreen mode Exit fullscreen mode

✔ Tells others: “Handle this exception when you call me”

** Custom Exceptions = Pro Level**

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

Enter fullscreen mode Exit fullscreen mode

✔ Makes your errors meaningful
✔ Great for large applications

*Real-World Use Cases
*

✔ Banking apps → prevent invalid transactions
✔ Login systems → handle wrong credentials
✔ File systems → manage missing files
✔ E-commerce → handle payment failures

Best Practices (Don’t Skip This)

✔ Catch specific exceptions (not generic Exception)
✔ Never leave catch blocks empty
✔ Don’t use exceptions for normal logic
✔ Always log errors
✔ Keep try blocks small
✔ Use custom exceptions when needed

Common Mistakes

✔ Catching everything blindly
✔ Ignoring exceptions
✔ Writing too many try-catch blocks
✔ Not understanding exception types

Final Thoughts

Good developers write code that works.
Great developers write code that keeps working even when things go wrong.

Exception handling is what separates the two.

✔ It makes your app stable
✔ It improves user trust
✔ It prepares you for real-world development

FAQs

✔ What is exception handling in Java?
It is a way to handle runtime errors without stopping the program.

✔ Checked vs unchecked exceptions?
Checked → compile-time, Unchecked → runtime.

✔ What does try-catch do?
It prevents your app from crashing by handling errors.

✔ Is finally always executed?
Yes, except in extreme cases like JVM shutdown.

✔ Why use custom exceptions?
To make your application logic clearer and more meaningful.

Final Tip

If you’re learning Java… don’t just write code that runs.
Write code that survives failure.

Top comments (0)