Chapter 6: Exceptions
Introduction
Learning Outcomes
Define an exception; classify runtime problems as Exception or Error.
Handle exceptions with try, catch, finally and try-with-resources; trace the flow step by step.
Explain how Throwable, Error, Exception and RuntimeException relate, and why catch order matters.
Tell checked from unchecked exceptions; apply the “catch or declare” rule.
Throw exceptions with throw, declare them with throws; trace how an exception propagates up the call stack.
Recognize common exception classes, write a custom exception class and read a stack trace.
Basics
What Is an Exception?
- An exception is an unexpected event that occurs while a program runs and disrupts its normal flow.
- Examples: a file that cannot be found, division by zero, an index outside an array, using a
nullreference. - Exceptions are created automatically by the Java runtime (the JVM) or explicitly by the programmer (
throw). - In Java an exception is an object: it carries its type, a message and where it happened.
- The exception mechanism lets you deal with abnormal situations in an orderly way.
A waiter learns in the kitchen that a dish has run out. He can't fix it, so he tells the manager. The manager either solves it (suggests another dish) or passes it further up.
Basics
Runtime Errors: Exception and Error
Compile errors stop a program from running at all; logic errors give no signal. A problem that arises while the program runs is thrown by the JVM as a Throwable object, which has two main branches.
| Branch | What it means | What the program can do | Example |
|---|---|---|---|
| Exception ( Exception) | An unusual condition the program can anticipate | Catch it and recover | 10 / 0, arr[5] (on a 3-element array), a missing file |
| Error ( Error) | A serious JVM- or system-level problem | Usually not caught; the program ends | StackOverflowError, OutOfMemoryError |
Exceptions and stack traces are among the most powerful tools for finding and fixing the cause of runtime errors (debugging).
Basics
Uncaught Exception: The Program Crashes
public class Crash { public static void main(String[] args) { int num = 10, den = 0; System.out.println("Start"); int result = num / den; System.out.println("Result: " + result); System.out.println("Done"); } }
Start
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Crash.main(Crash.java:5)- Line 5 divides an integer by zero; the JVM throws an
ArithmeticExceptionobject. - Nobody catches it, so the program terminates: “Result” and “Done” are never printed.
- The JVM prints the exception's type, message and location (class, method, line).
Basics
Two Ways to Deal with an Exception
The method puts the risky code in try and resolves the problem itself in catch.
Example: if the file is missing (FileNotFoundException), a file-reading method shows a message and goes on with default settings.
The method does not handle the exception; it declares it with throws in its signature. The exception becomes the caller's problem.
The caller faces the same choice: handle it or pass it up.
Basics
“Something Went Wrong”: With a Return Code
public static int indexOf(String[] names, String name) { for (int i = 0; i < names.length; i++) { if (names[i].equals(name)) { return i; } } return -1; } // in main String[] names = {"Ali", "Ayşe", "Can"}; System.out.println(indexOf(names, "Can")); int k = indexOf(names, "Ece"); // k = -1 System.out.println(names[k]);
2 java.lang.ArrayIndexOutOfBoundsException: Index -1 out of bounds for length 3
- Exceptions are how a program signals that “something went wrong”.
- But “wrong” is subjective: is a name that isn't found an error, or a normal result?
- When there is no match, this method returns
-1instead of throwing an exception. - If the caller forgets to check for
-1, the error shows up elsewhere, atnames[-1](output on the left).
Basics
Exceptions Instead of Return Codes
public static int find(String[] names, String name) { for (int i = 0; i < names.length; i++) { if (names[i].equals(name)) { return i; } } throw new IllegalArgumentException("Not found: " + name); } // in main try { System.out.println(find(names, "Ece")); } catch (IllegalArgumentException e) { System.out.println("Error: " + e.getMessage()); }
Error: Not found: Ece
- As a rule, avoid special return codes like
-1; prefer Java's exception mechanism. - Exceptions handle error cases clearly and effectively.
Why exceptions help
- Clear, consistent error handling; errors never mix with normal results
- More readable code, easier debugging
- More reliable code
try and catch
try and catch Statements
try { // Code that may fail int result = 10 / 0; // ArithmeticException } catch (ArithmeticException e) { // Handle the error System.out.println("Error: " + e.getMessage()); }
Error: / by zero
- The basic structure of error handling.
tryblock: code that may fail.catchblock: runs if an exception of the given type occurs insidetry, and handles it.catch (ArithmeticException e):erefers to the thrown exception object (like a parameter).- If an exception occurs, the rest of
tryis skipped; if none occurs,catchnever runs. - After catch, the program continues its normal flow.
try and catch · Step by step
try-catch Flow: Step by Step
Variables are created. den is zero: trouble ahead.
Normal code outside try runs.
We enter the try block; the first line runs fine.
10 / 0: the JVM creates an ArithmeticException object and throws it. No assignment happens.
Type matches: catch runs and e refers to the exception object. The “Result” line was skipped.
e.getMessage() → "/ by zero".
No crash: after catch, normal flow continues.
public class DivideDemo { public static void main(String[] args) { int num = 10, den = 0; System.out.println("Start"); try { System.out.println("Before divide"); int result = num / den; System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("Error: " + e.getMessage()); } System.out.println("Done"); } }
try and catch
Getting Information from the Exception Object
try { int[] arr = new int[3]; arr[5] = 7; } catch (ArrayIndexOutOfBoundsException e) { System.out.println(e.getMessage()); System.out.println(e); System.out.println(e.getClass().getSimpleName()); e.printStackTrace(); }
Index 5 out of bounds for length 3
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
ArrayIndexOutOfBoundsException
java.lang.ArrayIndexOutOfBoundsException: Index 5 out of bounds for length 3
at ExceptionDemo.main(ExceptionDemo.java:5)| Method | Returns |
|---|---|
getMessage() | Just the message (or null) |
toString() | Full class name + “: ” + message; println(e) uses it |
getClass() | The exception's actual class |
printStackTrace() | toString() + stack trace; writes to System.err |
getCause() | The exception that caused this one (if any) |
try and catch
Multiple catch Blocks
try { // Code that may fail } catch (ArithmeticException e) { // Handle ArithmeticException } catch (NullPointerException e) { // Handle NullPointerException } catch (Exception e) { // All other exceptions }
- A block of code can throw more than one type of exception.
- Add a separate
catchblock per type; each holds the response specific to that type. - When an exception is thrown, the catch blocks are tried top to bottom; the first match runs and the rest are skipped.
- “Match” means the thrown object is the catch type itself or a subclass (the
instanceofrule). - The final
catch (Exception e)is the general case that catches everything else.
try and catch
Chained catch Blocks: Order Matters
✗ General type first
try { int result = 10 / 0; } catch (Exception e) { System.out.println("General error"); } catch (ArithmeticException e) { System.out.println("Arithmetic error"); }
OrderError.java:7: error: exception ArithmeticException
has already been caught- If the catch types are related by inheritance, order matters: subclasses must come before superclasses.
ArithmeticExceptionis anException; the first block already catches it, so the second can never run. The compiler rejects this.- For unrelated types (
ArithmeticException,NullPointerException) order does not matter.
✓ Specific to general
} catch (ArithmeticException e) { System.out.println("Arithmetic error"); } catch (Exception e) { System.out.println("General error"); }
try and catch · Step by step
Which catch Runs?
1st call: parseInt("abc") → NumberFormatException. The division line is skipped.
The first catch matches and runs; the other catches are not checked.
Then finally.
2nd call: 10 / 0 → ArithmeticException.
The 1st catch doesn't match (✗), the 2nd does (✓).
3rd call: the array has one element; input[1] → ArrayIndexOutOfBoundsException.
The first two catches don't match, the third does; then finally.
static void divide(String[] input) { try { int x = Integer.parseInt(input[0]); int y = Integer.parseInt(input[1]); System.out.println("Result: " + (x / y)); } catch (NumberFormatException e) { System.out.println("Not a number: " + e.getMessage()); } catch (ArithmeticException e) { System.out.println("Zero: " + e.getMessage()); } catch (ArrayIndexOutOfBoundsException e) { System.out.println("Missing: " + e.getMessage()); } finally { System.out.println("finally ran"); } } // in main divide(new String[] {"10", "abc"}); divide(new String[] {"10", "0"}); divide(new String[] {"10"});
try and catch
One catch, Several Types (Java 7+)
try { Object o = "Hello"; Integer i = (Integer) o; } catch (ClassCastException | NullPointerException e) { System.out.println("Type or null error: " + e.getClass().getSimpleName()); }
Type or null error: ClassCastException
- Same response? Join the types with
|to avoid duplicate code. - In this block
eis implicitly final; it cannot be reassigned.
✗ Can't combine a subclass with its superclass
} catch (FileNotFoundException
| IOException e) {error: Alternatives in a multi-catch statement cannot be related by subclassing Alternative FileNotFoundException is a subclass of alternative IOException
catch (IOException e). It already covers the subtype.finally
The finally Block
try { // Code that may fail } catch (Exception e) { // All other exceptions } finally { // Always runs }
- Comes after the
tryandcatchblocks. - Runs in every case: whether or not an exception occurs, and whether or not it is caught.
- Even if
tryorcatchcontains areturn, it runs before the method exits. - Guarantees that certain steps run: resource management and cleanup, such as closing files, network and database connections.
trymust be followed by at least onecatchor afinally;try { } finally { }is valid.- The one exception:
System.exit()stops the JVM at once; finally does not run.
finally · Step by step
finally and return: Step by Step
Before println runs, its argument must be evaluated: divide(10, 2) is called.
The try block starts.
The division succeeds: s = 5.
return s: the return value 5 is ready, but the method doesn't end yet…
…first finally runs. catch was skipped (no exception).
Now 5 is returned and printed.
Second call: divide(10, 0).
try starts.
10 / 0 → exception! The rest of try (“try ended”, return s) is skipped.
catch matches and prints the message.
return -1: the value is ready, but again finally runs first.
finally runs this time too.
-1 is returned. So finally ran in both cases.
static int divide(int a, int b) { try { System.out.println("try started"); int s = a / b; System.out.println("try ended"); return s; } catch (ArithmeticException e) { System.out.println("catch: " + e.getMessage()); return -1; } finally { System.out.println("finally"); } } public static void main(String[] args) { System.out.println("Result = " + divide(10, 2)); System.out.println("Result = " + divide(10, 0)); }
finally
try-with-resources (Java 7+)
class Resource implements AutoCloseable { private String name; Resource(String name) { this.name = name; System.out.println(name + " opened"); } void use(int x) { System.out.println(name + " in use"); int s = 10 / x; } @Override public void close() { System.out.println(name + " closed"); } }
try (Resource r = new Resource("file")) { r.use(0); } catch (ArithmeticException e) { System.out.println("Error: " + e.getMessage()); }
file opened file in use file closed Error: / by zero
- A resource opened in
try (...)is closed automatically (close()) when the block ends, even after an exception. - The resource is closed before catch runs. Its class must implement
AutoCloseable, as streams,Scanner, NIO channels and database connections do; nofinallyornullcheck is needed. - This is the modern, safe way to do what
finallydid for closing resources.
finally · Step by step
Two Resources: Opening and Closing Order
Resource: its constructor prints “… opened”, use prints “… in use”, close() prints “… closed”.
The first resource is created: file opened.
The second resource is created. Resources are separated by semicolons and opened in the order written.
b.use(0): first “net in use” is printed, then 10 / 0.
Exception thrown: the rest of try (“try end”) is skipped. But the resources are closed before catch.
Closing happens in reverse order: b, opened last, closes first (close()).
Then a closes. Both resources were closed despite the exception.
Now catch runs: the exception is caught.
finally runs last. Order: open → use → close (reversed) → catch → finally.
try (Resource a = new Resource("file"); Resource b = new Resource("net")) { b.use(0); System.out.println("try end"); } catch (ArithmeticException e) { System.out.println("Error: " + e.getMessage()); } finally { System.out.println("finally"); }
finally
Nested try Blocks
try { // Outer try block try { // Inner try block // Code that may fail } catch (Exception e) { // Inner catch block } finally { // Inner finally block } } catch (Exception e) { // Outer catch block } finally { // Outer finally block }
A try block can contain another try block. If an exception occurs in the inner try:
- If one of the inner try's catches matches, it runs.
- Otherwise the exception moves outward; the first matching catch is found and runs.
- If no catch matches, the exception leaves the method; if nobody catches it, the JVM's default handler ends the program.
- In every case, the
finally(if any) at each level the exception passes through runs.
finally · Step by step
Nested try: The Exception Moves Outward
The outer try starts.
The inner try starts; s = null.
Calling a method on null → NullPointerException.
The inner catch only catches ArithmeticException: no match.
Before the exception leaves, the inner finally runs.
The exception reached the outer level; “Outer try cont.” was skipped. The outer catch matches.
The outer finally runs.
The exception was handled; the program continues normally.
public static void main(String[] args) { try { System.out.println("Outer try"); try { System.out.println("Inner try"); String s = null; System.out.println(s.length()); } catch (ArithmeticException e) { System.out.println("Inner catch"); } finally { System.out.println("Inner finally"); } System.out.println("Outer try cont."); } catch (NullPointerException e) { System.out.println("Outer catch: NPE"); } finally { System.out.println("Outer finally"); } System.out.println("Program goes on"); }
Hierarchy
The Exception Hierarchy
- Java's exception classes form a class hierarchy.
Throwableis the root of everything that can be thrown: only objects ofThrowableand its subclasses can be thrown withthrowand caught withcatch.Throwablehas two direct subclasses:ErrorandException.- A
catchblock catches the named type and all its subclasses (a natural result of inheritance). - Java lets you define your own custom exception classes: classes for application-specific situations join this hierarchy.
Exceptions of one family can be caught with a single supertype: catch (IOException e) catches FileNotFoundException and other I/O errors alike.
Hierarchy
The Exception Class Tree
Hierarchy
Error and Exception
Error
- Signals that the program has hit a serious problem it cannot recover from.
- Such situations usually cannot be handled and typically end the program.
- Examples: extreme cases such as running out of memory (
OutOfMemoryError), a call stack overflow, or a disk drive “vanishing”. - Catching them in application code is not recommended.
Exception
- Conditions the program can anticipate and often recover from.
- A missing file, a dropped network connection, invalid input, a
nullreference… - The type you are expected to handle with
try-catch. - Its subclass
RuntimeExceptionmostly represents programmer errors.
Both derive from Throwable, so both can be thrown. But the family that “should be handled” is Exception.
Kinds of Exceptions
Kinds of Exceptions
Checked by the compiler at compile time; the programmer must handle or declare them. They cover situations known in advance to be possible.
Not checked at compile time; they show up at run time. RuntimeException, Error and their subclasses.
Kinds of Exceptions
Checked Exceptions
- Must be handled or declared by the code: the “catch or declare” rule.
- Either list it with
throwsin the method header or handle it in atry-catch. - Derives from
Exceptionbut not fromRuntimeException. - The rule is enforced at compile time: break it and the program won't compile.
- Example: reading a file that doesn't exist. However correct the program is, the file may have been deleted, so the compiler demands a plan.
✗ Neither handled nor declared
public void readFile() { FileReader reader = new FileReader("data.txt"); }
error: unreported exception FileNotFoundException; must be caught or declared to be thrown
✓ Declared with throws
public void readFile() throws FileNotFoundException { // Read the file FileReader reader = new FileReader("data.txt"); }
Kinds of Exceptions
Handling a Checked Exception
public static void readFile2() { try { FileReader reader = new FileReader("data.txt"); // Read the file } catch (FileNotFoundException e) { // Checked exception handled here System.err.println("File not found: " + e.getMessage()); // Rethrow if needed: // throw e; } }
File not found: data.txt (The system cannot find the file specified)
- Here the method catches the exception itself; there is no
throwsin its signature. The caller doesn't have to do anything. System.err: the error output stream. Most IDEs show it in red.- The message comes from the operating system, so it differs on Windows and Linux.
throw e;: a caught exception can be rethrown if needed (say, after logging it). The method must then declarethrows FileNotFoundExceptionagain.
Kinds of Exceptions
Unchecked Exceptions
- Exceptions you are not required to handle or declare.
- They usually come from logic errors or programmer errors: dividing by zero, using
null, going past an array's bounds. - No
throwsclause ortry-catchis required; the compiler stays silent. - They derive from
RuntimeExceptionorError. - The right fix is usually not to catch them but to prevent them: check the divisor before dividing and
nullbefore use.
public void divide(int num, int den) { // Unchecked: ArithmeticException int result = num / den; }
Compiles; no throws needed. If den == 0, an exception occurs at run time.
public void divide(int num, int den) { if (den == 0) { // prevention System.out.println("Divisor cannot be 0"); return; } int result = num / den; }
Kinds of Exceptions
Checked, Unchecked, Error
| Checked | Unchecked | Error | |
|---|---|---|---|
| Superclass | Exception (except RuntimeException) | RuntimeException | Error |
| Checked by compiler? | Yes: handle or declare | No | No |
| Typical cause | Conditions outside the program (file, network, database) | Programmer error (null, bounds, division) | JVM / system problem |
| What to do | Catch and recover, or pass on with throws | Fix the code, validate input | Usually don't catch; end the program cleanly |
| Examples | IOException, SQLException, ClassNotFoundException | NullPointerException, ArithmeticException | OutOfMemoryError, StackOverflowError |
Throwing
Throwing an Exception
- When the Java runtime hits an unexpected situation, it creates an exception object and throws it to notify higher-level code.
- The programmer can do the same with the
throwkeyword. - An exception changes the normal flow: the lines after
throwdon't run; control jumps to a matchingcatch. - Many types can be thrown:
IOException,NullPointerException,IllegalArgumentException, your own custom classes… - The caller can catch a thrown exception with
try-catch. If it is never handled, the JVM ends the program and reports what went wrong and where.
Syntax
throw new Exception("This is an exception!");
new creates the exception object (the message goes to the constructor); throw throws it.
try { throw new Exception("This is an exception!"); } catch (Exception e) { System.out.println(e); }
java.lang.Exception: This is an exception!
Throwing
The Exception Type That Best Fits
class CustomException extends Exception { public CustomException(String message) { super(message); } } public static void check(int value) throws CustomException { if (value < 0) { // Check a condition and throw throw new CustomException("Value cannot be negative!"); } // Value is OK: carry on System.out.println("Value OK: " + value); } // in main try { check(5); check(-3); check(8); } catch (CustomException e) { System.out.println("Caught: " + e.getMessage()); }
Value OK: 5 Caught: Value cannot be negative!
- Choose the exception class that best represents the situation.
- For special scenarios you can create custom exception classes.
CustomExceptionis a subclass ofException, so it is checked. That is why the method signature needsthrows CustomException.- Once
check(-3)throws, the rest of try is skipped:check(8)is never called.
Throwing · Step by step
throw: An Exception Skips the Rest of try
main calls check(5) inside try; a new frame is pushed on the stack.
5 < 0 is false: the throw line is skipped.
“Value OK: 5” is printed; the method returns normally.
Next call: check(-3).
-3 < 0 is true.
new creates the exception object and throw throws it. Line 5 doesn't run; the method has no catch, so its frame is discarded.
The exception reached main; the rest of try (check(8)) is skipped and a matching catch is found.
getMessage() returns the message given to the constructor.
catch is done; the program continues its normal flow. check(8) was never called.
static void check(int value) throws CustomException { if (value < 0) { throw new CustomException("Value cannot be negative!"); } System.out.println("Value OK: " + value); } // in main try { check(5); check(-3); check(8); } catch (CustomException e) { System.out.println("Caught: " + e.getMessage()); }
Throwing
throw vs throws
throw | throws | |
|---|---|---|
| Purpose | Throws an exception (now) | Declares the exceptions a method may throw (possibly later) |
| Where | In the method body, as a statement | In the method signature, after the parameters |
| Followed by | A single object: throw new X("…"); | One or more types: throws X, Y |
| Example | throw new ArithmeticException("Division by zero"); | void divide(int x, int y) throws ArithmeticException |
✗ throws can't be used in the body
if (x < 0) { throws new IllegalArgumentException("negative"); }
error: illegal start of expression
✗ Checked exception thrown without being declared
static void f(int x) { if (x < 0) throw new Exception("negative"); }
error: unreported exception Exception; must be caught or declared to be thrown
Throwing
Calling Methods That Throw
A file-reading method
public void readFile() throws FileNotFoundException { // Read the file }
1) The caller handles it (preferred)
try { readFile(); } catch (FileNotFoundException e) { // Handle the missing file System.err.println("File not found: " + e.getMessage()); }
2) The caller declares it too (passes it on)
public void makeReport() throws FileNotFoundException { readFile(); }
- When calling a method, consider the exceptions declared in its signature and pick a suitable strategy.
- Put the call inside a suitable
try-catchblock. - Or have the caller declare the same type with
throws; the problem moves up a level. This only postpones the problem, so it is less preferred than catching. - Even
maincan declarethrows; an uncaught exception then ends the program.
Throwing · Step by step
Propagation: The Exception Unwinds the Call Stack
main calls compute(10) inside try.
A compute frame is pushed on the stack.
compute calls divide(10, 0).
divide is now on top of the stack.
10 / 0: the exception is born in divide. divide has no try → the rest of divide doesn't run and its frame is discarded.
The exception passes to the caller, compute. No try here either → “compute ended” is skipped and the frame is discarded.
The exception reaches main. The call is inside a try, so a matching catch is sought. The “Result” line is skipped.
catch matches: the exception is caught and propagation stops.
The program ends normally. Had nobody caught it, the JVM would have ended the program.
static int divide(int a, int b) { System.out.println("divide started"); int s = a / b; System.out.println("divide ended"); return s; } static int compute(int x) { System.out.println("compute started"); int r = divide(x, 0); System.out.println("compute ended"); return r; } public static void main(String[] args) { try { int result = compute(10); System.out.println("Result: " + result); } catch (ArithmeticException e) { System.out.println("main: " + e.getMessage()); } System.out.println("Program ended"); }
Throwing
How Does the JVM Handle an Exception?
- The JVM (or
throw) creates an exception object holding its type, its message and a stack trace of where it occurred. - In the method where it occurred, the JVM looks for an enclosing
trywith a compatiblecatch. - If none is found, the method ends at once (its
finallyruns, if any) and the exception passes to the calling method. The search continues down the call stack. - If a matching catch is found, it runs; the program continues after the catch.
- If
maindoesn't catch it either, the JVM's default handler prints the stack trace and ends the program (that thread).
Runtime Exceptions
RuntimeException Classes
RuntimeException and its subclasses represent exceptions caused by programmer errors or logic errors. They are not checked at compile time and need not be handled; still, the programmer should deliberately prevent or handle them.
| Class | When does it occur? | Example |
|---|---|---|
NullPointerException | Using a member of a null reference | String s = null; s.length(); |
ArrayIndexOutOfBoundsException | Index outside the array bounds | int[] a = new int[3]; a[5] = 1; |
ArithmeticException | Integer division by zero, overflow in exact arithmetic | 10 / 0 |
IllegalArgumentException | A method gets an invalid argument | new ArrayList<>(-1) |
NumberFormatException | Converting text that isn't a valid number | Integer.parseInt("abc") |
ClassCastException | Casting an object to a type it doesn't have | (Integer) obj |
Runtime Exceptions
NullPointerException
- Calling a method, accessing a field or taking
lengththrough anullreference causes this exception. - One of the most common bugs. To prevent it:
- An explicit check:
if (str != null) Objects.requireNonNull(x, msg): ifnull, throws an NPE immediately with a meaningful messageObjects.requireNonNullElse(x, fallback)(Java 9+): returns the fallback ifnull- The
Optionalclass (Java 8+): explicitly represents “there may be no value” - Libraries: Apache Commons Lang
StringUtilsoffersnull-safe string operations
- An explicit check:
String str = null; int length = str.length();
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "str" is null
null. The variable name appears when compiled with debug info (javac -g, IDEs); otherwise you see "<local1>".Runtime Exceptions
Working Safely with null
1String str = null; 2int length = str.length(); 3Objects.requireNonNull(str, "str must not be null"); 4Optional<String> optionalStr = Optional.ofNullable(str); 5length = optionalStr.map(String::length).orElse(0); 6String defaultValue = Objects.requireNonNullElse(str, "0"); 7if (str != null) { 8 System.out.println(str.length()); 9} 10System.out.println("Ali".equals(str));
| Line | Result (each line tried on its own) |
|---|---|
| 2 | NullPointerException: Cannot invoke "String.length()" because "str" is null |
| 3 | NullPointerException: str must not be null |
| 5 | length = 0 (no value → orElse(0)) |
| 6 | defaultValue = "0" |
| 7–9 | Condition false; nothing printed, no exception |
| 10 | false: the literal comes first, so a null argument is fine |
"Ali".equals(str) is safe; str.equals("Ali") throws an NPE when str is null. Use requireNonNull at the start of methods to catch the error at its source with a clear message.
Runtime Exceptions
ArrayIndexOutOfBoundsException
- Accessing an index outside the array's bounds: valid indexes are
0…length − 1; a negative index is invalid too. - A member of the
IndexOutOfBoundsExceptionfamily. Different classes of that family may be thrown:- array (
int[]),Vector, anArrays.asList(...)list →ArrayIndexOutOfBoundsException ArrayList.get→IndexOutOfBoundsException(the superclass)String.charAt→StringIndexOutOfBoundsException
- array (
- To catch them all:
catch (IndexOutOfBoundsException e).
Prevention: bound the loop with length
int[] numbers = {1, 2, 3}; for (int i = 0; i < numbers.length; i++) { System.out.print(numbers[i] + " "); }
1 2 3
i <= arr.length. The last pass accesses arr[length] and throws.Runtime Exceptions
Out of Bounds: Which Line, Which Exception?
1int[] numbers = {1, 2, 3}; 2int value = numbers[5]; 3ArrayList<String> list = new ArrayList<>(); 4String svalue = list.get(5); 5Vector<Integer> vector = new Vector<>(); 6value = vector.get(10); 7String[] names = {"Alice", "Bob", "Charlie"}; 8svalue = Arrays.asList(names).get(5); 9String str = "Hello"; 10char ch = str.charAt(10);
| Line | Exception thrown and its message |
|---|---|
| 2 | ArrayIndexOutOfBoundsExceptionIndex 5 out of bounds for length 3 |
| 4 | IndexOutOfBoundsExceptionIndex 5 out of bounds for length 0 |
| 6 | ArrayIndexOutOfBoundsExceptionArray index out of range: 10 |
| 8 | ArrayIndexOutOfBoundsExceptionIndex 5 out of bounds for length 3 |
| 10 | StringIndexOutOfBoundsExceptionIndex 10 out of bounds for length 5 |
Each line tried on its own. An empty ArrayList may have capacity, but its size is 0; get checks against the size.
Runtime Exceptions
ArithmeticException
- Represents an error during a mathematical operation; the best-known case is integer division by zero (
/and%). - The “exact” methods of
Maththrow on overflow:addExact,multiplyExact,toIntExact… BigDecimalprovides high-precision arithmetic; it throws on division by zero or when the quotient can't be represented exactly (1/3).doubleoperations don't throw:10.0 / 0→Infinity,Math.sqrt(-1)→NaN.Random.nextInt(0)throwsIllegalArgumentException, notArithmeticException: the bound must be positive.
int addition overflows, no exception occurs; the value wraps around:Integer.MAX_VALUE + 1 → -2147483648.If overflow must be detected, use
Math.addExact.Runtime Exceptions
Arithmetic Errors: Line by Line
1int result = 10 / 0; 2double dresult = Math.sqrt(-1); 3System.out.println(dresult); 4System.out.println(10.0 / 0); 5int t = Math.addExact(Integer.MAX_VALUE, 1); 6Random random = new Random(); 7int randomNumber = random.nextInt(0); 8BigDecimal num1 = new BigDecimal("10"); 9BigDecimal num2 = BigDecimal.ZERO; 10BigDecimal bresult = num1.divide(num2);
| Line | Result |
|---|---|
| 1 | ArithmeticException: / by zero |
| 3 | Prints NaN, no exception |
| 4 | Prints Infinity, no exception |
| 5 | ArithmeticException: integer overflow |
| 7 | IllegalArgumentException: bound must be positive |
| 10 | ArithmeticException: Division by zero |
Each line tried on its own. With floating-point numbers, division by zero yields special values (Infinity, NaN) under IEEE 754 rules, so double results need their own checks (Double.isNaN).
Runtime Exceptions
IllegalArgumentException
- Signals that a method received an invalid argument. It is an unchecked exception.
- Checking arguments and throwing stops the error at its source.
- Library examples:
Arrays.copyOfRange(d, 5, 2): start > endnew ArrayList<>(-1): negative capacitysetPriority(11)on aThread: priority must be 1–10new File(uri): the URI is not afile:URI
public void setAge(int age) { if (age < 0) { throw new IllegalArgumentException("Age cannot be negative"); } this.age = age; } public void setName(String name) { if (name.length() < 3) { throw new IllegalArgumentException("Min 3 characters"); } this.name = name; }
new FileReader("invalid/file/path") → FileNotFoundException; new Thread(null) throws nothing. Subclass: NumberFormatException.Runtime Exceptions
Illegal Argument: Line by Line
1setAge(-5); 2setName("Al"); 3int[] numbers = {1, 2, 3}; 4Arrays.copyOfRange(numbers, 5, 2); 5List<Integer> list = new ArrayList<>(-1); 6File file = new File(URI.create("http://example.com/a.txt")); 7Thread thread = new Thread(task); 8thread.setPriority(11);
| Line | Exception thrown (each line on its own) |
|---|---|
| 1 | IllegalArgumentException: Age cannot be negative |
| 2 | IllegalArgumentException: Min 3 characters |
| 4 | IllegalArgumentException: 5 > 2 |
| 5 | IllegalArgumentException: Illegal Capacity: -1 |
| 6 | IllegalArgumentException: URI scheme is not "file" |
| 8 | IllegalArgumentException (no message) |
A good message states the invalid value and what was expected: "Age cannot be negative: " + age. An exception with no message (line 8) makes debugging harder.
Runtime Exceptions
NumberFormatException
- Occurs when text being converted to a number doesn't represent a valid number.
Integer.parseInt,Double.parseDouble,Float.parseFloat,Short.parseShort,Long.parseLong,Byte.parseByteand thevalueOfmethods can throw it.- It also occurs when the value is outside the type's range:
Byte.parseByte("300"). - A subclass of
IllegalArgumentException. - User input always carries this risk: validate it first or catch the exception.
String strNumber = "abc"; int number = Integer.parseInt(strNumber); strNumber = "123abc"; number = Integer.parseInt(strNumber); String strDouble = "12.34abc"; double doubleValue = Double.parseDouble(strDouble); String strShort = "45xyz"; short shortValue = Short.parseShort(strShort);
| Call | NumberFormatException message |
|---|---|
Integer.parseInt("abc") | For input string: "abc" |
Integer.parseInt("123abc") | For input string: "123abc" |
Double.parseDouble("12.34abc") | For input string: "12.34abc" |
Short.parseShort("45xyz") | For input string: "45xyz" |
Runtime Exceptions
Safe Number Parsing
static int safeParse(String text, int fallback) { try { return Integer.parseInt(text.trim()); } catch (NumberFormatException e) { return fallback; } } // in main System.out.println(safeParse(" 42 ", 0)); System.out.println(safeParse("forty", 0)); System.out.println(safeParse("10.5", -1));
42 0 -1
- Parsing is checked in one place, a helper method; invalid input yields a default value.
trim()removes leading and trailing spaces:parseInt(" 42 ")alone would throw."10.5"is not anint; for decimals useDouble.parseDouble.- Pick a default that can't be confused with a valid result; if it can, passing the exception to the caller is the better choice.
Runtime Exceptions · Step by step
parseInt and catch: Three Inputs
First call: text " 7 " (spaces at both ends), fallback 0.
trim() drops the spaces; "7" becomes a number and 7 is returned from inside try.
Second call: "seven".
parseInt throws on text that isn't digits; return never ran.
catch matches: the fallback 0 is returned. The exception doesn't leave the method.
Third call: "7.5", fallback −1.
A dot is not a digit: "7.5" is not a valid int.
−1 is returned. The caller carries on with the fallback instead of an exception.
static int safeParse(String text, int fallback) { try { return Integer.parseInt(text.trim()); } catch (NumberFormatException e) { return fallback; } } System.out.println(safeParse(" 7 ", 0)); System.out.println(safeParse("seven", 0)); System.out.println(safeParse("7.5", -1));
Runtime Exceptions
ClassCastException
- Occurs when you cast an object to a type it is not.
- What counts is the object's actual type, not the variable's:
Object obj = "Hello"is aStringobject. - Raw collections (
ArrayList,Map,Set) accept anything; the cast fails when an element of the wrong type is retrieved. Sorted collections (TreeSet,TreeMap) also throw when an incomparable element is added. - Prevention: generics (
ArrayList<String>) catch the wrong type at compile time; check withinstanceofbefore casting.
1Object obj = "Hello"; 2Integer number = (Integer) obj; 3ArrayList list = new ArrayList(); 4list.add("Hello"); 5number = (Integer) list.get(0); 6Map map = new HashMap(); 7map.put("key", "Value"); 8Integer value = (Integer) map.get("key"); 9Set set = new HashSet(); 10set.add("Hello"); 11value = (Integer) set.iterator().next(); 12Object[] objArray = new String[5]; 13Integer[] intArray = (Integer[]) objArray;
Lines 2, 5, 8, 11 and 13 each throw ClassCastException, for example:
class java.lang.String cannot be cast to class java.lang.Integer
Runtime Exceptions
instanceof Before Casting
Classic form
Object obj = "Hello"; if (obj instanceof Integer) { Integer num = (Integer) obj; System.out.println("Number: " + num); } else { System.out.println("obj is not an Integer"); }
obj is not an Integer
Pattern matching (Java 16+)
if (obj instanceof Integer num) { System.out.println("Number: " + num); }
With generics, at compile time
ArrayList<String> list = new ArrayList<>();
list.add("Hello");
Integer n = (Integer) list.get(0);error: incompatible types: String cannot be converted to Integer
Checked Classes
Checked Exception Classes
They represent situations, mostly caused by conditions outside the program, that the code must handle and recover from properly. The compiler requires them to be handled.
| Class | Package | When? |
|---|---|---|
FileNotFoundException | java.io | The file to open doesn't exist or can't be opened |
IOException | java.io | General input/output error (superclass) |
SQLException | java.sql | Database access error |
ParseException | java.text | Error while parsing text against a format |
ClassNotFoundException | java.lang | A class to be loaded by name was not found |
InterruptedException | java.lang | A waiting thread was interrupted (Thread.sleep) |
NotSerializableException | java.io | An attempt to write a non-serializable object |
Checked Classes
FileNotFoundException
try { FileReader fileReader = new FileReader("file.txt"); } catch (FileNotFoundException e) { // Handle the missing file System.out.println(e); }
java.io.FileNotFoundException: file.txt (The system cannot find the file specified)
- Occurs when a file to be opened cannot be found (or is a folder, or can't be read).
- A subclass of
IOException;catch (IOException e)catches it too. - A relative path (
"file.txt") is resolved against the program's working directory. In IDEs this is usually the project folder, so the file may be “in the wrong folder”. - Typical response: tell the user and ask for another name, or carry on with defaults.
Checked Classes
IOException
try { BufferedReader reader = new BufferedReader(new FileReader(path)); String line; while ((line = reader.readLine()) != null) { System.out.println(line); } reader.close(); } catch (IOException e) { // Handle the I/O error e.printStackTrace(); }
first line second line
- Represents a general I/O error; it has many subclasses such as
FileNotFoundException. - Problem: if
readLine()throws,reader.close()never runs; the file stays open (a resource leak).
✓ With try-with-resources
try (BufferedReader reader = new BufferedReader(new FileReader(path))) { String line; while ((line = reader.readLine()) != null) { System.out.println(line); } } catch (IOException e) { System.out.println(e.getMessage()); }
Checked Classes
SQLException
try { Connection connection = DriverManager.getConnection("jdbc:mysql://localhost/school"); PreparedStatement preparedStatement = connection.prepareStatement("SELECT user_id FROM users"); // Run the query and process the results ResultSet resultSet = preparedStatement.executeQuery(); while (resultSet.next()) { // Process the results System.out.println("User ID: " + resultSet.getInt("user_id")); } // Close the connection connection.close(); } catch (SQLException e) { // Handle the SQLException System.out.println(e); }
- Thrown when a database operation fails: no connection, bad SQL syntax, missing table, missing driver…
getMessage(),getSQLState()andgetErrorCode()give details.
java.sql.SQLException: No suitable driver found for jdbc:mysql://localhost/school
A connection is a resource too; close it with try-with-resources.
Checked Classes
ParseException and ClassNotFoundException
ParseException (java.text)
Thrown when text doesn't match the expected format during parsing.
try { SimpleDateFormat form = new SimpleDateFormat("dd/MM/yy"); Date date = form.parse("01-01-2022"); } catch (ParseException e) { // Handle the parse error System.out.println(e); }
java.text.ParseException: Unparseable date: "01-01-2022"
The format expects /; the text has -.
ClassNotFoundException
Thrown when a class to be loaded by name (Class.forName) can't be found.
try { Class.forName("java.util.Scanner"); System.out.println("Scanner loaded"); // Try to load a missing class Class.forName("com.example.NonExistentClass"); } catch (ClassNotFoundException e) { System.out.println(e); }
Scanner loaded java.lang.ClassNotFoundException: com.example.NonExistentClass
Checked Classes
NotSerializableException
class Point { // not Serializable int x = 3, y = 4; } // in main try (ObjectOutputStream outputStream = new ObjectOutputStream(new ByteArrayOutputStream())) { // Try to serialize the object Point notSerializableObj = new Point(); outputStream.writeObject(notSerializableObj); } catch (NotSerializableException e) { System.out.println(e); } catch (IOException e) { System.out.println("Other I/O error: " + e); }
java.io.NotSerializableException: Point
- Serialization: converting an object to a byte stream (to write it to a file or send it over a network) and restoring it later.
- A class that implements
Serializableis serializable; writing an object of a class that doesn't throws this exception. - An (indirect) subclass of
IOException, so its catch goes before theIOExceptioncatch.
✓ Fix
class Point implements Serializable { int x = 3, y = 4; }
Error Classes
Error Classes
- Unchecked types for system-level problems that fundamentally affect the program's normal operation.
- They usually stem not from a line of application code but from the state of the JVM and its environment.
- Thrown by the JVM; handling or declaring them is not recommended. Letting the program end cleanly is the better approach.
- Still, since they are
Throwables, they can technically be caught.
| Error | When? |
|---|---|
OutOfMemoryError | Heap memory is exhausted |
StackOverflowError | The call stack overflowed: usually infinite recursion |
AssertionError | An assert condition is false (only with -ea) |
NoClassDefFoundError | A class present at compile time is missing at run time |
Error Classes
Error Examples
static void recurse() { recurse(); // no base case } public static void main(String[] args) { try { recurse(); } catch (StackOverflowError e) { System.out.println("SOE -> " + e); } try { long[] arr = new long[Integer.MAX_VALUE]; } catch (OutOfMemoryError e) { System.out.println("OOM -> " + e); } int age = -5; assert age >= 0 : "Negative age: " + age; System.out.println("assert passed"); }
SOE -> java.lang.StackOverflowError OOM -> java.lang.OutOfMemoryError: Requested array size exceeds VM limit assert passed
SOE -> java.lang.StackOverflowError OOM -> java.lang.OutOfMemoryError: Requested array size exceeds VM limit Exception in thread "main" java.lang.AssertionError: Negative age: -5
- If recursion has no base case, every call adds a new frame until the stack is full.
assertis disabled by default; enable it with-ea. It checks assumptions during development. (Catching here is for demonstration only.)
Custom Exceptions
Custom Exception Classes
public class MyException extends Exception { // Constructor public MyException(String message) { super(message); } }
| Superclass | Result |
|---|---|
extends Exception | Checked: the caller must handle it; recoverable business-rule violations |
extends RuntimeException | Unchecked: misuse, programmer error |
- Developers can create custom exception classes to manage unexpected situations specific to their programs.
- An object of any class extending
Throwablecan be thrown. Usually, though, you extendExceptionorRuntimeException, notErrororThrowabledirectly. - The constructor passes the message up with
super(message), sogetMessage()works. - End the name with
…Exception; it should describe the situation. - You can add extra fields (a missing amount, a bad value): an exception is an ordinary class.
Custom Exceptions
Throwing and Catching a Custom Exception
public class MyExceptionTest { public static void main(String[] args) { try { doWork(); } catch (MyException e) { System.out.println("Caught: " + e.getMessage()); } } public static void doWork() throws MyException { if (true) { throw new MyException("Custom error occurred."); } } }
Caught: Custom error occurred.
MyExceptionextendsException, so it is checked:throws MyExceptionis required in the signature ofdoWork().mainwraps the call intry, choosing to “handle” it.if (true)is only for the demo: code after an unconditionalthrowwould cause an “unreachable statement” error.- In real programs the condition checks a business rule: is the balance enough, is the grade within 0–100, is the user name empty…
Custom Exceptions · Step by step
Custom Exception: A Bank Account
The Account object is created on the heap; acct refers to it.
withdraw(30): is 30 > 100? No; no exception.
The balance becomes 70.0 and is printed.
withdraw(90): is 90 > 70? Yes.
An exception object is created on the heap (message and deficit = 20.0) and thrown. The balance is unchanged.
withdraw's frame is discarded; withdraw(10) is skipped. catch matches: e refers to the same object.
The exception object's data is used. An exception is just an ordinary object.
class Account { private double balance; Account(double balance) { this.balance = balance; } public void withdraw(double amount) throws LowBalanceException { if (amount > balance) { throw new LowBalanceException( "Insufficient funds", amount - balance); } balance -= amount; System.out.println("Balance: " + balance); } } // in main Account acct = new Account(100); try { acct.withdraw(30); acct.withdraw(90); acct.withdraw(10); } catch (LowBalanceException e) { System.out.println(e.getMessage() + ", deficit: " + e.getDeficit()); }
Custom Exceptions
A Custom Exception That Carries Data
class LowBalanceException extends Exception { private double deficit; public LowBalanceException(String msg, double deficit) { super(msg); // kept in Throwable this.deficit = deficit; } public double getDeficit() { return deficit; } }
- The class used in the previous trace: besides the message, it carries the missing amount.
- The catching code can use it to respond sensibly: “You are 20 TL short; try anyway?”
- A return code like
-1could never carry this much information. - A checked type was chosen: insufficient balance is a foreseeable situation the caller must deal with.
Stack Trace
Stack Trace
- A report of which method calls were active and where the exception occurred.
- It holds the exception's type and message, and for each call the class and method name, the file name and the line number.
- For an uncaught exception the JVM prints it to the console (
System.err); you can also print it withe.printStackTrace(). - It is the most important clue for understanding and fixing a bug.
Exception in thread "main" java.lang.NullPointerException
at com.example.MyClass.myMethod(MyClass.java:10)
at com.example.MyClass.main(MyClass.java:6)Reading it: main (line 6) called myMethod; the exception occurred at line 10 of myMethod. com.example is the package, MyClass the class.
Stack Trace
Reading a Stack Trace
1public class TraceDemo { 2 static int len(String text) { 3 return text.length(); 4 } 5 static void show(String name) { 6 System.out.println(name + ": " + len(name)); 7 } 8 public static void main(String[] args) { 9 show("Ali"); 10 show(null); 11 System.out.println("Done"); 12 } 13}
- First line: type and message:
textisnull. - First
at: where the exception was born (line 3). - Reading down, the call chain:
main(10) →show(6) →len(3). - Look at your own lines first; the real cause is often further down: line 10 passed the
null.
Ali: 3
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "text" is null
at TraceDemo.len(TraceDemo.java:3)
at TraceDemo.show(TraceDemo.java:6)
at TraceDemo.main(TraceDemo.java:10)Stack Trace · Step by step
Where Does a Stack Trace Come From?
main calls show("Ali") at line 9.
show calls len(name) at line 6. Each frame remembers its current line.
"Ali".length() = 3 is returned; the frame is removed.
“Ali: 3” is printed and show ends.
main calls show(null) at line 10.
null is passed as an argument; no problem yet.
null.length(): an NPE is thrown. The stack now holds three frames: len:3, show:6, main:10.
When the exception object is born, it records the stack: each frame becomes an at line, the top one first.
Nobody caught it: all three frames were discarded; the JVM printed the stack trace and ended the program. “Done” is never printed.
public class TraceDemo { static int len(String text) { return text.length(); } static void show(String name) { System.out.println(name + ": " + len(name)); } public static void main(String[] args) { show("Ali"); show(null); System.out.println("Done"); } }
Stack Trace
Best Practices for Exception Handling
Where possible, catch the expected type instead of catch (Exception e), and respond to each kind appropriately.
An empty catch { } hides the error. At least log it or tell the user.
Close files, connections and other resources with try-with-resources or finally.
Check for null, bounds and zero; fix the code instead of catching RuntimeException.
Don't use exceptions for ordinary tasks such as leaving a loop; exceptions are for exceptional situations.
State the bad value and what was expected: "Grade must be 0-100: 120".
Catch an exception where it can be resolved; otherwise pass it on with throws.
Logging exceptions to a file makes it easier to trace errors later.
Stack Trace
final, finally and finalize
| What? | Role | |
|---|---|---|
final | Keyword | Variable: can't be reassigned · method: can't be overridden · class: can't be subclassed |
finally | Keyword (block) | Cleanup block after try that runs whether or not an exception occurs |
finalize() | Method of Object | The garbage collector could call it before removing an object. When it runs is unpredictable; deprecated since Java 9. |
finally, not finalize().Summary
Summary
| Concept | Key point |
|---|---|
| Exception | Disrupts normal flow at run time; an object with type, message and location |
try / catch | Risky code in try; the first matching catch runs, rest of try skipped |
| catch order | Subclass before superclass; the reverse won't compile. A | B (Java 7+) |
finally | Always runs, even before return; for cleanup |
| try-with-resources | try (Resource r = …): an AutoCloseable resource closes itself |
| Hierarchy | Throwable → Error | Exception → … RuntimeException |
| Checked | Exception (not Runtime): handle or declare with throws |
| Unchecked | RuntimeException, Error: not required; prevent |
throw / throws | Throw (body, object) / declare (signature, types) |
| Propagation | Uncaught exception passes to the caller; if main doesn't catch it, the program ends |
| Custom exception | class X extends Exception + super(message) |
| Stack trace | Type + message, then the call chain; the first at line is the origin |
Summary
Common Mistakes
new FileReader(name) with no try/throws: unreported exception FileNotFoundException; must be caught or declared to be thrown.
catch (Exception e), then catch (ArithmeticException e): exception ArithmeticException has already been caught.
catch (FileNotFoundException e) on a try with no file operation: exception FileNotFoundException is never thrown in body of corresponding try statement.
A try with no catch or finally: 'try' without 'catch', 'finally' or resource declarations.
A line right after throw in the same block: unreachable statement.
Printing result, declared inside try, after the block: cannot find symbol. Declare it before the try.
catch (Exception e) { } compiles, but the error vanishes without a trace.
throw "error"; → incompatible types: String cannot be converted to Throwable.
Summary
Practice Problems (1)
Problem 1: What is the output?
static int f() { try { System.out.print("A"); int x = 5 / 0; System.out.print("B"); return 1; } catch (ArithmeticException e) { System.out.print("C"); return 2; } finally { System.out.print("D"); } } // in main System.out.println(" " + f());
Problem 2: What is the output?
try { String s = "12a"; int n = Integer.parseInt(s); System.out.println("Number: " + n); } catch (IllegalArgumentException e) { System.out.println("IAE"); } catch (Exception e) { System.out.println("Exception"); }
Problem 3
What happens if the two catch blocks in Problem 2 swap places?
Show answers
ACD 2: “A”; the division throws (B andreturn 1are skipped); catch prints “C” and prepares 2; finally prints “D”; 2 is returned.IAE:NumberFormatExceptionis a subclass ofIllegalArgumentException.- Compile error:
exception IllegalArgumentException has already been caught.
Summary
Practice Problems (2)
Problem 4: What is the output?
static void a() { System.out.print("a1 "); b(); System.out.print("a2 "); } static void b() { System.out.print("b1 "); throw new IllegalStateException("!"); } // in main try { a(); System.out.print("m "); } catch (IllegalStateException e) { System.out.print("caught" + e.getMessage()); } finally { System.out.println(" end"); }
The exception is born in b(); neither b() nor a() has a try. Which prints run and which are skipped? When does finally run?
Show answer
a1 b1 caught! end
The exception travels b → a → main: “a2” and “m” are skipped. The catch in main catches it, then finally prints “ end” and ends the line.
Summary
Practice Problems (3)
Problem 5: Final value of sum?
int[] d = {4, 0, 2}; int sum = 0; for (int i = 0; i <= d.length; i++) { try { sum += 12 / d[i]; } catch (ArithmeticException e) { sum += 100; } catch (ArrayIndexOutOfBoundsException e) { sum += 1000; } } System.out.println(sum);
Problem 6: What is the output?
try { throw new RuntimeException("X"); } finally { System.out.println("F"); }
Show answers
- 1109: 12/4 = 3, 12/0 → +100, 12/2 = 6,
d[3]→ +1000. Each pass has its own try, so the loop keeps going. - First F, then
Exception in thread "main" java.lang.RuntimeException: X: finally runs, but the exception is not caught, so the program ends.
Summary
Exercises (1)
- Write
int readAge(String text): if the text isn't a number, letNumberFormatExceptionoccur; if negative, throwIllegalArgumentException. Use two catches to print messages for"20","-3","twenty". - Write a checked exception
InvalidGradeExceptionandsetGrade(int grade), which throws it for grades outside 0–100. - In Exercise 1, what if the catch order is
IllegalArgumentException, thenNumberFormatException?
Answers / hints
int age = Integer.parseInt(text); if (age < 0) throw new IllegalArgumentException("Negative age: " + age); return age;· Output:Age: 20,Negative age: -3,Not a number: twenty. The NFE catch must come first.class InvalidGradeException extends Exception { … super(msg); }·void setGrade(int grade) throws InvalidGradeException { if (grade < 0 || grade > 100) throw new InvalidGradeException("Grade must be 0-100: " + grade); … }·setGrade(120)→Grade must be 0-100: 120.- Compile error:
exception NumberFormatException has already been caught(NFE is a subclass of IAE).
Summary
Exercises (2)
- Classify as checked or unchecked:
IOException,NumberFormatException,SQLException,NullPointerException,FileNotFoundException,ClassCastException,StackOverflowError. - Rewrite code that closes a
BufferedReaderinfinallyusing try-with-resources. - What should
double average(int[] grades)do for an empty array? Return0or throw an exception? Which one?
Answers / hints
- Checked:
IOException,SQLException,FileNotFoundException· unchecked:NumberFormatException,NullPointerException,ClassCastException,StackOverflowError(Error). try (BufferedReader r = new BufferedReader(new FileReader(path))) { … } catch (IOException e) { … }:close()is called automatically.- 0 could be confused with a valid average (like the −1 return code). An empty array is an invalid argument:
throw new IllegalArgumentException("Empty array");
Summary
References
- Oracle, The Java Tutorials: Lesson: Exceptions (Catching and Handling Exceptions; The try-with-resources Statement; Unchecked Exceptions — The Controversy).
- J. Gosling et al., The Java Language Specification, Java SE 21 Edition, Chapter 11: Exceptions; 14.20 The try statement.
- Oracle, Java SE 21 API Documentation:
java.lang.Throwable,Exception,RuntimeException,Error. - P. Deitel and H. Deitel, Java: How to Program, 11th ed., Pearson (Chapter 11: Exception Handling: A Deeper Look).
- K. Sierra, B. Bates and T. Gee, Head First Java, 3rd ed., O'Reilly (Risky Behavior: exception handling).
- C. S. Horstmann, Core Java, Volume I: Fundamentals, 12th ed., Pearson (Chapter 7: Exceptions, Assertions, and Logging).
- J. Bloch, Effective Java, 3rd ed., Addison-Wesley (Chapter 10: Exceptions, Items 69–77).