top of page

Welcome
to NumpyNinja Blogs

NumpyNinja: Blogs. Demystifying Tech,

One Blog at a Time.
Millions of views. 

Exception Handling in Java: A Complete Guide

May 1, 2025
4 min read


In software development, things don’t always go as planned. Files might go missing, a user might input invalid data, or a network request could time out. These unexpected problems are known as exceptions, can cause programs to crash or behave unpredictably—unless they're properly handled.

This is where exception handling comes in. It's a powerful mechanism in Java that allows developers to detect and respond to errors in a controlled and graceful way, keeping applications stable and user-friendly.


Understanding Exception in Java:

An Exception is an event that disrupts the normal flow of the program. It is an object which is thrown at runtime whenever an error occurs. They arise due to various reasons, such as invalid user input, attempting to access a file that doesn’t exist, dividing by zero, or exceeding an array’s bounds. Java provides a structured way to catch and handle these exceptions so your program can continue or shut down gracefully.


Exception Handling Mechanisms:

Java provides the try-catch-finally block to  handling runtime errors, ensuring that programs can recover gracefully rather than crashing abruptly.

  • try and catch Blocks

    The try block contains code that may generate an exception, while the catch block handles that exception.

  • finally Block

    The finally block is always executed, whether an exception occurs or not. It's commonly used for cleanup operations (eg: closing database connections).


    Syntax:

try {
		    // Code that might throw an exception
		} catch (ExceptionType e) {
		    // Handling code
		} finally {
		    // Optional: code that runs regardless of an exception
		}
  • throw Keyword

    The throw keyword is used inside a method to explicitly throw an exception. It enables you to create and trigger exceptions based on specific conditions.

    Example:

public class ThrowExample {
		 public static void checkAge(int age) {
		 if (age < 18) {
		 throw new IllegalArgumentException("Age must be at least 18!");
		        }
		        System.out.println("Access granted.");
		    }
		  public static void main(String[] args) {
		        checkAge(16); // Will throw IllegalArgumentException
		    }
		}

  • throws Keyword

    The throws keyword is used in the method signature to indicate that a method may throw one or more exceptions. It alerts the caller that it must handle the exception.

    Example:

public class ThrowsExample {
		    public static void readFile() throws IOException {
		        FileReader fr = new FileReader("nonexistent.txt");
		    }
		    public static void main(String[] args) {
		        try {
		            readFile();
		        } catch (IOException e) {
		            System.out.println("File not found!");
		        }
		    }
		}

Types of Exception in Java

Java divides exceptions into three main categories:


  1. Checked Exceptions (Compile-Time Exceptions)

    These are exceptions that the compiler forces you to handle either by catching them using a try-catch block or declaring them with the throws keyword. If they are not handled, the program will not compile.

    Examples:

    • IO Exception - Occurs when an input/output operation fails .

    • SQLException – Related to database access errors.

    • FileNotFoundException – When a requested file is missing.

    • ClassNotFoundException – When the JVM cannot find a referenced class.


    Example java code:

public class CheckedExample {
		    public static void main(String[] args) throws IOException {
		        FileReader fr = new FileReader("nonexistentfile.txt");
		    }
		}
  1. Unchecked exceptions: (Runtime Exceptions)

    Unchecked exceptions occur at runtime and do not need to be explicitly handled in the code. They typically indicate programming errors. These exceptions are not checked at compile-time.

    Examples:

    • NullPointerException – Occurs when accessing a null reference.

    • ArrayIndexOutOfBoundsException – When trying to access an invalid index in an array.

    • ArithmeticException – Results from arithmetic errors like division by zero.

    • NumberFormatException – When parsing an invalid number format.

    • IllegalArgumentException – Raised when a method receives an invalid argument.


    Example java code:

public class UncheckedExample {
		    public static void main(String[] args) {
		        try {
		            int result = 10 / 0;
		        } catch (ArithmeticException e) {
		            System.out.println("Cannot divide by zero!");
		        } finally {
		            System.out.println("Execution complete.");
		        }
		    }
		}
  1. Errors (System-Level Failures)

    Errors indicate serious problems that applications typically cannot recover from. They are system-level failures rather than exceptions. It indicate problems with the JVM or hardware.

    Examples:

    • StackOverflowError – Occurs when recursion runs infinitely.

    • OutOfMemoryError – When the JVM runs out of memory.

    • VirtualMachineError – Represents critical JVM-related errors.

    • AssertionError – Thrown when an assertion fails in code.


    Example code in java:

public class StackOverflowExample {
		    public static void recursiveMethod() {
		        recursiveMethod(); // Infinite recursion
		    }

		    public static void main(String[] args) {
		        try {
		            recursiveMethod();
		        } catch (StackOverflowError e) {
		         System.out.println("Caught a StackOverflowError! " + e);
		        }
		    }
		}

Custom Exceptions in Java

 Custom Exceptions allow developers to define their own exception classes tailored to specific application needs.

This provides more meaningful error messages and makes debugging easy.


Creating Custom Exception:

There are two main ways to create a custom exception in Java, depending on whether you want a checked or unchecked exception.

  1. Checked Custom Exception

    A checked exception is one that must be either caught or declared in the method using throws. You create it by extending the Exception class.

    Steps:

    • Extend the Exception class.

    • Define constructors.

    • Throw and handle it where needed.


    Example code :

// Custom exception class extending Exception (Checked Exception)
		class InvalidAgeException extends Exception {
		    public InvalidAgeException(String message) {
		        super(message);
		    }
		}
		public class CustomExceptionExample {
		    // Method that validates age
		 public static void checkAge(int age) throws InvalidAgeException {
		  if (age < 18) {
throw new InvalidAgeException("Age must be at least 18 to register.");
		        }
		        System.out.println("Registration successful!");
		    }

		    public static void main(String[] args) {
		        try {
		          checkAge(16); // This will trigger the custom exception
		        } catch (InvalidAgeException e) {
		       System.out.println("Caught Exception: " + e.getMessage());
		        }
		    }
		}
  1. Unchecked Custom Exception

    An unchecked exception is a runtime exception that the compiler doesn't force you to catch. You create it by extending the RuntimeException class.

    Example:

// Custom unchecked exception
	public class InvalidScoreException extends RuntimeException {
		public InvalidScoreException(String message) {
		        super(message);
		    }
		}
		// Usage
	public class Main {
	public static void main(String[] args) {
	int score = -5;

	if (score < 0 || score > 100) {
	throw new InvalidScoreException("Score must be between 0 and 100.");
		        }
		    }
		}

Conclusion:

Exception handling is not just about fixing errors — it's about writing resilient, maintainable, and user-friendly code. With Java’s structured exception handling, you can prepare for the unexpected and prevent small bugs from becoming big failures.


Thanks for reading the blog!

Happy Learning!


 
 

+1 (302) 200-8320

NumPy_Ninja_Logo (1).png

Numpy Ninja Inc. 8 The Grn Ste A Dover, DE 19901

© Copyright 2025 by Numpy Ninja Inc.

  • Twitter
  • LinkedIn
bottom of page