Java Exception Handling: A Guide with Best Practices and Examples
In this guide, you will learn how to effectively manage exceptions in Java.
We will examine step by step how to use the try-catch-finally, throw and throws structures, the Java Exception Hierarchy, creating a custom exception and best practices.
🧠 Technical Summary
Subject: Java Exception Handling mechanism
Purpose: Safely manage errors that disrupt program flow (e.g. file not found, network error, null values)
Solved Problem: Preventing the program from crashing unexpectedly
Steps:
- Learn the concept of exception
- Apply the words try, catch, finally, throw, throws
- Know the exception hierarchy
- Discover what's new in Java 7 (try-with-resources, multi-catch)
- Create custom exception classes
🚨 What is an Exception in Java?
An exception is an event that occurs during program execution and disrupts the normal flow.
Java manages these situations with an object-oriented system.
Example error scenarios:
- User entered incorrect data
- The file cannot be found
- Network disconnection
- Hardware or memory error
🔑 Java Exception Handling Keywords
| Keyword | Description |
|---|---|
throw | It throws an exception manually in the code. |
throws | Declares exceptions that may be thrown in the method signature. |
try | It covers the block of code that may cause an error. |
catch | It catches and processes certain types of errors. |
finally | It always works, whether there are errors or not. |
💻 Sample Code: Exception Throwing and Catching
package com.genixnode.exceptions;
import java.io.FileNotFoundException;
import java.io.IOException;
public class GenixNodeIstisnaOrnegi {
public static void main(String[] args) throws FileNotFoundException, IOException {
try {
testException(-5);
testException(-10); // Önceki hata nedeniyle çalışmaz
} catch(FileNotFoundException e) {
e.printStackTrace();
} catch(IOException e) {
e.printStackTrace();
} finally {
System.out.println("Kaynaklar serbest bırakılıyor...");
}
testException(15); // try-catch dışında -> programı sonlandırır
}
public static void testException(int i) throws FileNotFoundException, IOException {
if (i < 0) throw new FileNotFoundException("Negatif tamsayı: " + i);
else if (i > 10) throw new IOException("Sadece 0–10 arası desteklenir");
}
}
➡️ Error is thrown with throw, method is warned with throws. ➡️ finally runs in all cases, freeing up resources.
🧩 Java Exception Hierarchy
| Genre | Description | Example |
|---|---|---|
| Error | Systemic errors are usually not detected and are caused by unprogrammed reasons. | OutOfMemoryError, StackOverflowError |
| Checked Exception | These are predictable errors and must be caught with try-catch or reported with throws. | IOException, FileNotFoundException |
| Runtime Exception | It arises from coding errors, there is no compile time requirement. | NullPointerException, ArrayIndexOutOfBoundsException |
⚙️ Java 7 Innovations
1. Try-with-Resources
try (MyResource mr = new MyResource()) {
System.out.println("Kaynak oluşturuldu ve kullanılacak");
} catch (Exception e) {
e.printStackTrace();
}
➡️ Resources are closed automatically, finally is not required.
2. Multiple Catch Blocks
catch (IOException | SQLException ex) {
logger.error(ex);
throw new MyException(ex.getMessage());
}
➡️ You can catch more than one error type in a single line.
🧱 Creating a Custom Exception
public class MyException extends Exception {
private String errorCode = "Bilinmeyen_Hata";
public MyException(String message, String errorCode) {
super(message);
this.errorCode = errorCode;
}
public String getErrorCode() {
return this.errorCode;
}
}
➡️ This class carries special error codes as well as error messages. ➡️ It is Checked Exception because it derives from Exception.
💡 Best Exception Management Practices
| Practical | Description |
|---|---|
| Use specific Exception | Types like FileNotFoundException clearly show the source of the error. |
| Launch Early (Fail-fast) | Catch errors before they occur. |
| Catch Late | Capture only where you can meaningfully process it. |
| Close resources | Use try-with-resources or finally. |
| Avoid empty catch blocks | Be sure to log the error message. |
| Use custom exception | It facilitates code readability and error management. |
| Consider performance | Don't throw unnecessary exceptions. |
| Document with Javadoc | Specify which exceptions may occur with the @throws tag. |
💬 Frequently Asked Questions (FAQ)
- Can the try block be used alone?
No, it must be accompanied by catch or finally.
- What is Checked Exception?
These are predictable errors in the code; must be caught or thrown away.
- What is Runtime Exception?
It is caused by a programming error and usually involves situations such as NullPointerException.
- What does finally do?
It closes resources, works even if there is an error.
- Why use Custom Exception?
It provides more understandable error management with special error types.
✅ Result
Java Exception Handling makes your applications more robust and professional. You can improve the reliability of your code by learning the try-catch-finally structure, correct exception types, and best practices.
☁️ Try it now: Create a Java development environment on the GenixNode platform and test exception handling examples.
yaml

