Single logo
  • Courses
  • Blog
  • About
Join on SkoolJoin on Skool

In this topic

Java
  • Install Java 25 (JDK) and IntelliJ IDEA, Then Run Your First Program
  • Use Claude Agent, Copilot or Junie Inside IntelliJ IDEA
  • Java Hello World with Maven: What the JDK Does and What Maven Adds
  • Java Variables, Keywords and Naming Rules
  • Maven in IntelliJ: pom.xml, Dependencies and the Build Lifecycle
  • Java Primitive Types and Memory: What int x = 5 Really Does
  • Java Strings and Text Blocks: Quotes, Concatenation and parseInt
  • Java Operators: Arithmetic, a++ vs ++a, Precedence, && || and the Ternary
  • Java Type Casting: Widening, Narrowing and Converting Text to Numbers
  • Java Practice Lab: A Cafe Bill with Variables, Operators and Casting
  • Java if, else and switch: Braces, Else-If Ladders and the Modern Switch
  • Java Loops: for, while, do-while and for-each
  • Java break, continue and Nested Loops
  • What's New in Java 21 to 25: Compact Source Files and Sequenced Collections
  • Java Arrays: Indexes, Default Values, Loops and 2D Grids
  • Java Methods and Overloading: Parameters, return and Pass-by-Value
  • Java Scope, Code Blocks and the Call Stack
  • Read User Input in Java with Scanner (and the Leftover Enter Trap)
  • Java Practice Lab: A Gym Weekly Tracker with Loops, Arrays and Methods
  • Debugging Java in IntelliJ: Stack Traces, Breakpoints and a Better AI Prompt
  • Java var: Let Java Infer the Type
  • Push and Pull in IntelliJ: Two Developers, One GitHub Repository, a Rejected Push and a Conflict
  • Java Classes and Objects: One Blueprint, Many Cars
  • Java Constructors and the this Keyword
  • Java Instance Methods, Getters, Setters and toString
  • Java static: Fields, Methods and Blocks Shared by the Whole Class
  • Java Packages and Imports: Every Class Has an Address
  • Java Access Modifiers and Encapsulation: Private Data, Public Methods
  • Java final and Immutable Objects: Assign Once, Share Safely
  • Java Strings as Objects: The String Pool, == vs equals, StringBuilder and printf
  • Java Practice Lab: A Library Book Catalogue with final Fields and StringBuilder
  • Java Inheritance: extends, super and the Order Objects Are Built
  • Java Method Overriding, @Override and the Object Class
  • Java Polymorphism: Upcasting, Dynamic Dispatch and Downcasting
  • Java Composition: Has-A vs Is-A
  • Java Abstract Classes: A Parent That Leaves One Blank
  • Java Interfaces: Contracts and Multiple Inheritance
  • Java Nested, Inner and Anonymous Classes
  • Java Enums with Fields, Methods and switch
  • Java Practice Lab: Payment Processing with an Interface, an Abstract Class and an Enum
  • Java Records: A Whole Data Class in One Line
  • Java Sealed Classes and Interfaces
  • Java Pattern Matching with instanceof and switch
  • Java Record Patterns: Unpacking a Record
  • Java equals and hashCode: Why a HashSet Needs Both
  • From Arrays to Collections: The Java Collections Framework Map
  • Java Wrapper Classes and Autoboxing
  • Java ArrayList: The Stretchy Array
  • Java LinkedList vs ArrayList: Nodes or an Array
  • Java Sets: HashSet, LinkedHashSet and TreeSet
  • Java Sorting with Comparable and Comparator
  • Java Maps: HashMap, LinkedHashMap and TreeMap
  • Java Stacks, Queues and Deques: ArrayDeque and PriorityQueue
  • Choosing a Java Collection: Immutable and Sequenced Collections
  • Java Exception Handling: try, catch and finally
  • Java throw, throws, Checked vs Unchecked and Custom Exceptions
  • Java try-with-resources and Clean Error Handling
  • Java Generics: Type-Safe Containers
  • Java Generic Methods, Bounded Types and Wildcards
  • Java Lambdas and Functional Interfaces
  • Java Built-in Functional Interfaces: Predicate, Function, Consumer, Supplier
  • Java Optional: Saying Maybe Without null
  • Java Streams I: filter, map and reduce
  • Java Streams II: Collectors, groupingBy and flatMap
  • Why Concurrency: Processes, Threads and the Main Thread in Java
  • Creating Threads in Java: Thread, Runnable and Lambdas
  • Java Thread Lifecycle: sleep, join and interrupt
  • Java Race Conditions and synchronized
  • Java volatile and Atomic Variables
  • Java ExecutorService and Thread Pools
  • Java Callable, Future and CompletableFuture
  • Java Locks, Deadlock and tryLock
  • Java Concurrent Collections and Virtual Threads
  • Why Slow Work Belongs off the Request Thread: 202 Accepted and a Job Id in Spring Boot
  • Virtual Threads in Spring Boot: One Property, and the Connection Pool Trap
  • @Async, Named TaskExecutors and Structured Concurrency in Spring Boot
  • Java Files and Directories with NIO.2: Path and Files
  • Reading and Writing Text Files in Java
  • Java Structured Data: Reading and Writing JSON and CSV
  1. Blog
  2. /
  3. Java
  4. /
  5. Exceptions

Java throw, throws, Checked vs Unchecked and Custom Exceptions

A deposit of -20 is fine for Java but wrong for the bank, so throw rejects it. An InsufficientFundsException declines Maria's 500 with "Short by 380.0", the stack trace shows withdraw, settle and main, and the compiler refuses a checked call nobody handles.

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Exceptions

What you will learn

  • Raise an exception for your own rule with throw
  • Write a custom checked exception that extends Exception
  • Declare a method that can fail with throws and read its stack trace
  • Tell checked from unchecked exceptions and what the compiler demands for each

Before you start

  • Java exception handling: try, catch and finally
  • Java inheritance: extends and super

In try, catch and finally, Java threw the exception for us. Now we raise our own, warn the callers that a method can fail, and see why Java makes you handle some exceptions but not others.

Your rule, your throw

package org.studyeasy.s03l20;

public class Ex01_Throw {
    static double deposit(double balance, double amount) {
        if (amount <= 0) {
            // Java sees nothing wrong here, our rule does: stop and say why
            throw new IllegalArgumentException("Bad amount " + amount);
        }
        return balance + amount;
    }

    public static void main(String[] args) {
        System.out.println("Balance: " + deposit(100, 50));
        try {
            System.out.println("Balance: " + deposit(100, -20));
        } catch (IllegalArgumentException e) {
            System.out.println("Rejected: " + e.getMessage());
        }
    }
}
Balance: 150.0
Rejected: Bad amount -20.0

Depositing -20 is perfectly valid arithmetic, so Java won't complain. It's only wrong for our logic. throw new IllegalArgumentException(...) creates the exception object and throws it. Nothing after the throw runs, so return balance + amount never executes for -20, and the catch prints the message.

Make your own exception

package org.studyeasy.s03l20;

// extends Exception -> CHECKED: every caller must handle it or declare it
public class InsufficientFundsException extends Exception {
    public InsufficientFundsException(String message) {
        super(message);     // getMessage() returns this text
    }
}

A custom exception is an ordinary class that extends Exception. The constructor passes the message to super, which stores it; that's the text e.getMessage() returns later.

throws warns, throw raises

package org.studyeasy.s03l20;

public class Account {
    private double balance;

    public Account(double balance) {
        this.balance = balance;
    }

    // throws: the signature tells every caller this method can fail
    public void withdraw(double amount) throws InsufficientFundsException {
        if (amount > balance) {
            throw new InsufficientFundsException("Short by " + (amount - balance));
        }
        balance -= amount;
    }

    public double getBalance() {
        return balance;
    }
}

throws, with an s, goes on the signature and warns every caller that withdraw can fail. throw, without the s, goes in the body and raises one exception. When the check fails, balance -= amount never runs.

Account maria = new Account(200);
try {
    maria.withdraw(80);
    System.out.println("Left: " + maria.getBalance());
    maria.withdraw(500);
    System.out.println("Paid 500");          // skipped
} catch (InsufficientFundsException e) {
    System.out.println("Declined: " + e.getMessage());
}
Left: 120.0
Declined: Short by 380.0

80 leaves 120. Then 500 is more than 120, so withdraw throws, "Paid 500" is skipped, and the message says short by 380 (500 minus 120).

Where did it come from? The stack trace

package org.studyeasy.s03l20;

public class Ex03_StackTrace {
    static void settle(Account account, double amount) throws InsufficientFundsException {
        account.withdraw(amount);          // the exception passes through here
    }

    public static void main(String[] args) {
        Account maria = new Account(120);
        System.out.println("Settling order 41");
        try {
            settle(maria, 500);
        } catch (InsufficientFundsException e) {
            e.printStackTrace();           // the path the exception travelled, on stderr
        }
    }
}
Settling order 41
org.studyeasy.s03l20.InsufficientFundsException: Short by 380.0
    at org.studyeasy.s03l20.Account.withdraw(Account.java:13)
    at org.studyeasy.s03l20.Ex03_StackTrace.settle(Ex03_StackTrace.java:5)
    at org.studyeasy.s03l20.Ex03_StackTrace.main(Ex03_StackTrace.java:12)

settle also says throws, so it passes the exception on instead of handling it. e.printStackTrace() prints the path the exception travelled to standard error (IntelliJ shows it in red): newest call first, so withdraw, then settle, then main, each with its line number. Withdraw has no catch, so its frame is removed; settle has none either, so its frame goes too; main's catch matches the type and runs.

A checked exception nobody handles

package org.studyeasy.s03l20;

public class Ex04_Unhandled {
    public static void main(String[] args) {
        Account maria = new Account(200);
        maria.withdraw(80);                // checked exception, nobody handles it
        System.out.println("Left: " + maria.getBalance());
    }
}
src\main\java\org\studyeasy\s03l20\Ex04_Unhandled.java:6: error: unreported exception InsufficientFundsException; must be caught or declared to be thrown
        maria.withdraw(80);                // checked exception, nobody handles it
                      ^
1 error

This one doesn't even start. 80 is less than 200, so the call would never fail, but withdraw declares a checked exception and this call ignores it, so javac refuses. There are two ways out: wrap the call in try and catch, or add throws InsufficientFundsException to main. (The project excludes this file in pom.xml so the rest still builds.)

Checked or unchecked

Exception at the top. Under it, InsufficientFundsException extends Exception directly and is checked: the compiler makes you catch it or declare it. RuntimeException also sits under Exception; everything under it, such as IllegalArgumentException and ArithmeticException, is unchecked and handling is optional. Exception InsufficientFundsException RuntimeException IllegalArgumentException ArithmeticException CHECKED: catch it or declare it the compiler checks before it runs UNCHECKED: handling is optional
Under Exception but not RuntimeException: checked. Under RuntimeException: unchecked.

Our exception extends Exception directly, so it's checked: javac makes every caller catch it or declare it, before the program runs. RuntimeException also sits under Exception, and everything under it is unchecked. IllegalArgumentException and ArithmeticException are two of them; they usually point to a bug in the calling code. Remove the try/catch from Ex01_Throw and it still compiles, then crashes at run time. Handling them is good practice, but Java won't force you.

Recap

You writeWhereWhat it does
throw new X(...)method bodyraises one exception
throws Xmethod signaturewarns every caller
extends Exceptionyour classchecked: the caller must handle or declare it
extends RuntimeExceptionyour classunchecked: handling is optional
e.printStackTrace()catch blockprints the path, newest call first

An AI can write this syntax for you; knowing which kind you need helps you ask for the right thing. Next: closing files and connections safely with try-with-resources.

Keep going in Java · 56 of 79

Previous
Java Exception Handling: try, catch and finally
Next post
Java try-with-resources and Clean Error Handling
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Related posts

Java Exception Handling: try, catch and finally

A bill splitter crashes on a table with zero guests and table 9 never runs. try and catch keep it going, the exception travels back through the call stack to the matching catch, two catches handle 0 and "four", and finally prints the receipt either way.

Java try-with-resources and Clean Error Handling

Put the resource in the brackets after try and Java closes it when the block ends. A LogFile that implements AutoCloseable prints Closed bills.log on success and, when share(90, 0) throws, before the catch runs. Plus four habits for clean errors.

On this page

  • Your rule, your throw
  • Make your own exception
  • throws warns, throw raises
  • Where did it come from? The stack trace
  • A checked exception nobody handles
  • Checked or unchecked
  • Recap
Community · Free to join
Single logo

StudyEasy AI Community

Hosted onSkool

Learn AI engineering, share what you build, and connect with other learners.

  • Free resources: lesson files, notebooks and code

  • Ask questions and join engineering discussions

  • Meet real people learning and building with AI

Join free on Skool

Related course on Udemy

FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE

Java 25, JSP, Hibernate, Spring Boot 4, REST APIs, React and Spring AI.View on Udemy ↗: FULL STACK JAVA : JAVA + JSP + SPRING BOOT AI + REACT + VIBE (paid course, opens in a new tab)

Single logo

Empowering Education, One Course at a Time

About
About usContact us
Legal
Terms of UsePrivacy Policy

© 2026 StudyEasy Organization. All rights reserved.