Support Online
Skip to main content

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:

  1. Learn the concept of exception
  2. Apply the words try, catch, finally, throw, throws
  3. Know the exception hierarchy
  4. Discover what's new in Java 7 (try-with-resources, multi-catch)
  5. 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

KeywordDescription
throwIt throws an exception manually in the code.
throwsDeclares exceptions that may be thrown in the method signature.
tryIt covers the block of code that may cause an error.
catchIt catches and processes certain types of errors.
finallyIt 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

GenreDescriptionExample
ErrorSystemic errors are usually not detected and are caused by unprogrammed reasons.OutOfMemoryError, StackOverflowError
Checked ExceptionThese are predictable errors and must be caught with try-catch or reported with throws.IOException, FileNotFoundException
Runtime ExceptionIt 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

PracticalDescription
Use specific ExceptionTypes like FileNotFoundException clearly show the source of the error.
Launch Early (Fail-fast)Catch errors before they occur.
Catch LateCapture only where you can meaningfully process it.
Close resourcesUse try-with-resources or finally.
Avoid empty catch blocksBe sure to log the error message.
Use custom exceptionIt facilitates code readability and error management.
Consider performanceDon't throw unnecessary exceptions.
Document with JavadocSpecify which exceptions may occur with the @throws tag.

💬 Frequently Asked Questions (FAQ)

  1. Can the try block be used alone?

No, it must be accompanied by catch or finally.

  1. What is Checked Exception?

These are predictable errors in the code; must be caught or thrown away.

  1. What is Runtime Exception?

It is caused by a programming error and usually involves situations such as NullPointerException.

  1. What does finally do?

It closes resources, works even if there is an error.

  1. 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