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

Chaand Sheikh

·27 November 2026·Updated 28 November 2026Exceptions

What you will learn

  • Explain what an exception is and why an uncaught one stops the program
  • Wrap risky code in try and handle it in catch with getMessage
  • Trace how an exception travels back up the call stack to a matching catch
  • Use several catch blocks and a finally block that runs on both paths

Before you start

  • Java methods and overloading
  • Java scope, code blocks and the call stack

Sometimes a line simply can't finish, and an unhandled problem crashes the whole program. Exception handling lets your application deal with the problem and carry on.

One zero stops everything

package org.studyeasy.s03l19;

public class Ex01_BillCrash {
    static int share(int bill, int guests) {
        return bill / guests;      // guests = 0: no answer exists
    }

    public static void main(String[] args) {
        System.out.println("Table 4: " + share(120, 4));
        System.out.println("Table 7: " + share(90, 0));
        System.out.println("Table 9: " + share(60, 3));   // never runs
    }
}
Table 4: 30
Exception in thread "main" java.lang.ArithmeticException: / by zero
    at org.studyeasy.s03l19.Ex01_BillCrash.share(Ex01_BillCrash.java:5)
    at org.studyeasy.s03l19.Ex01_BillCrash.main(Ex01_BillCrash.java:10)

Table 4 works. Table 7 has zero guests, and bill / guests can't finish (integer division by zero, as in operators). Java throws an exception: an object it creates when a line cannot finish, here an ArithmeticException with the message "/ by zero". Nothing catches it, so the program stops there, and table 9 never runs.

Catch it, keep going

package org.studyeasy.s03l19;

public class Ex02_CatchIt {
    static int share(int bill, int guests) {
        return bill / guests;
    }

    public static void main(String[] args) {
        System.out.println("Table 4: " + share(120, 4));
        try {
            System.out.println("Table 7: " + share(90, 0));
            System.out.println("Table 7 paid");   // skipped
        } catch (ArithmeticException e) {
            System.out.println("Table 7 skipped: " + e.getMessage());
        }
        System.out.println("Table 9: " + share(60, 3));   // still runs
    }
}
Table 4: 30
Table 7 skipped: / by zero
Table 9: 20

The risky call goes inside try. If it fails, the catch block for that exception type runs, and e.getMessage() tells you why. The rest of the try block is skipped after the failing line, so "Table 7 paid" never prints. After the catch, the program carries on, and table 9 is served.

The type matters. Write catch (NumberFormatException e) instead and the ArithmeticException isn't caught: the program crashes as before.

The exception goes back to the caller

main calls share(90, 0), pushing a frame on the stack. 90 / 0 throws an ArithmeticException object with message "/ by zero". share has no catch, so its frame is removed and the exception goes back to main. In main the rest of the try block is skipped, the matching catch runs, and the program continues with table 9. share(90, 0): 90 / 0 no catch here: frame removed main try: rest skipped catch (ArithmeticException e) runs ArithmeticException message: "/ by zero" thrown goes back to the caller then: "Table 9: 20"
A frame with no matching catch is removed, and the exception keeps going back until a catch matches its type.

main calls share(90, 0) and a new frame goes on the call stack. The division can't finish, so Java creates the exception object. share has no catch, so its frame is removed and the exception goes back to main. There the type matches the catch, the catch runs, and the program continues.

Two ways to fail, two catches

package org.studyeasy.s03l19;

public class Ex03_MultiCatch {
    public static void main(String[] args) {
        String[] guests = {"4", "0", "four"};   // typed in by staff
        for (String text : guests) {
            try {
                int count = Integer.parseInt(text);
                System.out.println("Each pays " + 120 / count);
            } catch (NumberFormatException e) {
                System.out.println("'" + text + "' is not a number");
            } catch (ArithmeticException e) {
                System.out.println("Cannot split: no guests");
            }
        }
        System.out.println("All tables done");
    }
}
Each pays 30
Cannot split: no guests
'four' is not a number
All tables done

"four" spelled out makes parseInt throw a NumberFormatException; "0" makes the division throw an ArithmeticException. Java runs the first catch whose type matches, so each problem gets its own message, and the loop finishes every table. Delete the NumberFormatException catch and "four" crashes the program.

finally runs either way

package org.studyeasy.s03l19;

public class Ex04_Finally {
    static void payTable(int bill, int guests) {
        try {
            System.out.println("Each pays " + bill / guests);
        } catch (ArithmeticException e) {
            System.out.println("Cannot split: no guests");
        } finally {
            System.out.println("Receipt printed");   // on BOTH paths
        }
    }

    public static void main(String[] args) {
        payTable(120, 4);
        payTable(90, 0);
    }
}
Each pays 30
Receipt printed
Cannot split: no guests
Receipt printed

With 4 guests the try succeeds and the catch is skipped. With 0 the catch handles it. The finally block runs both times. Even when the catch has the wrong type and the program crashes, "Receipt printed" still prints first. Use finally for clean-up that must always happen.

Recap

BlockRuns when
tryalways starts; the rest is skipped once something is thrown
catch (Type e)only when that type is thrown; e.getMessage() gives the reason
several catchesone per kind of failure; the first match wins
finallyon success and on failure

You don't need to memorise the syntax; an AI can write a try/catch for you. What matters is knowing what each part does. Next: throwing your own exceptions in throw, throws and custom exceptions.

Keep going in Java · 55 of 79

Previous
Choosing a Java Collection: Immutable and Sequenced Collections
Next post
Java throw, throws, Checked vs Unchecked and Custom Exceptions
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 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.

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

  • One zero stops everything
  • Catch it, keep going
  • The exception goes back to the caller
  • Two ways to fail, two catches
  • finally runs either way
  • 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.