Core Java · Chapter 25 of 48

throw, throws and custom exceptions

By the end of this chapter you can throw your own exceptions with clear messages, choose checked or unchecked, keep the original cause, and close resources automatically with try-with-resources. Build it in your browser: a real editor and terminal, AI that explains, and tests that tell you when it works.

  • Part: Core Java
  • 5 tasks
  • Java
  • In the all labs plan

The first 2 chapters of Core Java are free. This one comes with the all labs plan.

Why you need this

Last Friday the Bengaluru counter sold eleven bun maska. It had eight. The stock code printed a warning nobody read and carried on, the stock went to minus three, and the evening shift promised buns that did not exist. Ravi wants the sale stopped, and the person at the counter told exactly what is short.

With what you know so far, you can catch other people's exceptions, but a method of your own can only report trouble by returning a special value (a -1, a false, a null) that the caller is free to ignore. That is exactly what happened on Friday. Nothing forced anyone to handle the shortage, and nothing said which item ran out.

What you build: 5 tasks

Each task has tests. You write the code in the lab's editor and press Check.

  1. Task 1

    OutOfStockException.java: give the exception a clear message

    In OutOfStockException.java, make the constructor give the exception the message "Only ", the number left, a space, the item, " left, asked for " and the number wanted, so getMessage() returns it. The exception stays checked: it keeps extending Exception, not RuntimeException, and item(), wanted() and left() keep returning what was passed in.

    For example, new OutOfStockException("Bun maska", 3, 2) has the message Only 2 Bun maska left, asked for 3, and ("Parle-G", 5, 0) has Only 0 Parle-G left, asked for 5.

  2. Task 2

    Stock.java: throw the right exception when stock is taken

    In Stock.java, make take(item, qty) take qty of the item off the stock. Throw an IllegalArgumentException when qty is less than 1 or when the item is not stocked here, and an OutOfStockException, built from the item, qty and how many are left, when fewer than qty are left. Taking the last ones is fine. When it throws, the stock does not change.

    For example, with 3 Bun maska and 40 Parle-G, taking 2 Bun maska leaves 1; taking 2 more throws an OutOfStockException for Bun maska and still leaves 1; taking 0 or -1 Parle-G, or 1 Samosa, throws an IllegalArgumentException; taking all 40 Parle-G leaves 0.

  3. Task 3

    Stock.java: wrap a bad stock file line in an exception with its cause

    In StockFileException.java, make the constructor keep the cause as well as the message, so getCause() returns it. Then in Stock.java, make load(lines) read one item=count per line, like Bun maska=12, and return a new Stock with those counts; spaces around the item and the count are fine. A line without an equals sign, or with a count that is not a whole number, throws a StockFileException (unchecked) with the message "Bad stock line ", the line number counted from 1, ": " and the line as it was, and the original exception as its cause, never null.

    For example, Bun maska=12 and " Parle-G = 40 " give 12 Bun maska and 40 Parle-G. Bun maska=12 then Parle-G=lots throws with the message Bad stock line 2: Parle-G=lots and a NumberFormatException as the cause; Samosa 8 throws with Bad stock line 1: Samosa 8, with a cause too.

  4. Task 4

    Stock.java: run a sale inside a shift with try-with-resources

    In Stock.java, make runShift(station, log, stock, item, qty) open a Shift for the station with try-with-resources, take qty of the item from the stock, record "sold ", qty, a space and the item in the shift, and return qty. When the stock throws an OutOfStockException, add "short of " and the item to the log and return 0. Any other exception goes to the caller. Either way the shift is closed, and it is closed before the shortage is handled.

    For example, a sale of 2 Bun maska at SBC returns 2 and leaves the log open SBC, SBC: sold 2 Bun maska, close SBC. A shortage at NDLS returns 0 and leaves open NDLS, close NDLS, short of Bun maska. An IllegalArgumentException at CSMT reaches the caller and leaves open CSMT, close CSMT.

  5. Task 5 · interview question

    Interview: Stock.java, predict the order two resources close in

    In Stock.java, make predictLog() return the entries the code in its comment adds to the log, in order, written exactly as they are added.

    The check runs the same code and compares your list with the real log.

What you will learn

  • throw and throws: raise an exception yourself, and declare the checked ones a method can throw.
  • Custom exceptions: your own exception class, with a message and fields the catcher can use.
  • Causes: wrapping a low-level exception without losing it.
  • try-with-resources: an object closed for you, whatever happens.

More in Core Java

Build "throw, throws and custom exceptions" yourself

Tapri runs chai counters at railway stations, and every counter runs a Java program you write. A real editor and terminal in your browser, AI that explains, and a Check that says when it works.

The first 2 chapters of Core Java are free. This one comes with the all labs plan.