An exception is an error that happens while a program is running: division by zero, wrong input, accessing an array element that does not exist, a file that does not exist. If an exception is not handled, the program stops. This lesson explains how exceptions are caught, how you report them yourself and how you make your own exception.
Before you start: what you need to know first – methods, inheritance. How to learn: type in and run each example, and try to solve the tasks at the end on your own first; open the hint and the solution only after that. All the programs are in Java (Java 17 or newer); each one has been compiled and run and gives the output shown.
What happens when an exception is not handled
The following program fails already in the second line of the main method, and the last statement is never run:
public class Main {
public static void main(String[] args) {
int[] array = {10, 20, 30};
System.out.println(array[3]); // index 3 does not exist
System.out.println("End of the program");
}
}
A message with the name of the exception and the line where it happened appears on the screen:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 3 out of bounds for length 3
at Main.main(Main.java:4)
This printout (the stack trace) is the most useful information when looking for a mistake: it says what happened and where.
Exception
When it happens
ArithmeticException
integer division by zero
ArrayIndexOutOfBoundsException
an array index out of range
NullPointerException
calling a method through a reference that is null
NumberFormatException
Integer.parseInt("12a")
InputMismatchException
Scanner expects a number, but text was entered
FileNotFoundException
the file does not exist
Catching an exception: try and catch
Code that may cause an exception is put in a try block. If an exception happens, execution jumps to the matching catch block, and the program carries on.
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String[] inputs = {sc.next(), sc.next(), sc.next()};
for (String s : inputs) {
try {
int number = Integer.parseInt(s); // may throw NumberFormatException
int result = 100 / number; // may throw ArithmeticException
System.out.println("100 / " + number + " = " + result);
} catch (NumberFormatException e) {
System.out.println("'" + s + "' is not a whole number");
} catch (ArithmeticException e) {
System.out.println("Division by zero: " + e.getMessage());
}
}
System.out.println("The program finished normally.");
}
}
Input:20 abc 0
Output:
100 / 20 = 5
'abc' is not a whole number
Division by zero: / by zero
The program finished normally.
There can be several catch blocks; they are checked in order. Several kinds of exceptions can also be caught with one block: catch (NumberFormatException | ArithmeticException e).
Example: safe number input
A common use: the program asks for a number until the user enters a correct value.
import java.util.Scanner;
public class Main {
static int readGrade(Scanner sc) {
while (true) {
System.out.print("Grade (1-5): ");
String s = sc.next();
try {
int x = Integer.parseInt(s);
if (x >= 1 && x <= 5)
return x;
System.out.println("The grade must be from 1 to 5.");
} catch (NumberFormatException e) {
System.out.println("That is not a number.");
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int grade = readGrade(sc);
System.out.println("Grade entered: " + grade);
}
}
Example run (the user enters x, 7 and 4):
Grade (1-5): x
That is not a number.
Grade (1-5): 7
The grade must be from 1 to 5.
Grade (1-5): 4
Grade entered: 4
The finally block and try-with-resources
The finally block is always run – both when an exception happened and when it did not. It is used to release resources (closing a file, a database connection).
public class Main {
static int divide(int a, int b) {
try {
return a / b;
} catch (ArithmeticException e) {
System.out.println("error: division by zero");
return 0;
} finally {
System.out.println("finally for " + a + "/" + b); // runs even after return
}
}
public static void main(String[] args) {
System.out.println(divide(10, 2));
System.out.println(divide(10, 0));
}
}
Output:
finally for 10/2
5
error: division by zero
finally for 10/0
0
For resources there is a shorter form, try-with-resources: an object created in the brackets after try is closed automatically at the end of the block.
import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
public class Main {
public static void main(String[] args) {
// the FileWriter closes itself at the end of the try block
try (FileWriter f = new FileWriter("result.txt")) {
f.write("First line\n");
f.write("Second line\n");
} catch (IOException e) {
System.out.println("Error while writing: " + e.getMessage());
}
try {
for (String line : Files.readAllLines(Path.of("result.txt")))
System.out.println("> " + line);
Files.readAllLines(Path.of("missing.txt"));
} catch (IOException e) {
System.out.println("Cannot read: " + e.getMessage());
}
}
}
Output:
> First line
> Second line
Cannot read: missing.txt
Reporting an error: throw and throws
A method can report an error itself with the throw statement. This, for example, stops an object from getting a state that is not allowed:
public class Main {
static class Account {
private double balance;
void deposit(double amount) {
if (amount <= 0)
throw new IllegalArgumentException("The amount must be positive");
balance += amount;
}
void withdraw(double amount) {
if (amount > balance)
throw new IllegalStateException("Not enough money (balance " + balance + ")");
balance -= amount;
}
}
public static void main(String[] args) {
Account r = new Account();
r.deposit(1000);
try {
r.withdraw(300);
r.withdraw(900);
System.out.println("This is not printed");
} catch (IllegalStateException e) {
System.out.println("Refused: " + e.getMessage());
}
try {
r.deposit(-50);
} catch (IllegalArgumentException e) {
System.out.println("Refused: " + e.getMessage());
}
}
}
Output:
Refused: Not enough money (balance 700.0)
Refused: The amount must be positive
Java has two kinds of exceptions:
unchecked (subclasses of RuntimeException) – mistakes in the program, such as NullPointerException; they do not have to be caught;
checked (e.g. IOException) – expected external errors; the compiler requires them to be caught or the method header to say throws IOException.
Your own exception
In the example, JMBG is the Serbian 13-digit personal identification number.
public class Main {
// your own exception: it extends Exception (a checked exception)
static class InvalidIdNumberException extends Exception {
private static final long serialVersionUID = 1L; // version marker (recommended for exception classes)
InvalidIdNumberException(String message) {
super(message);
}
}
// throws: the method announces that it may throw this exception
static void check(String idNumber) throws InvalidIdNumberException {
if (idNumber.length() != 13)
throw new InvalidIdNumberException("The JMBG must have 13 digits, but it has " + idNumber.length());
for (char c : idNumber.toCharArray())
if (!Character.isDigit(c))
throw new InvalidIdNumberException("The JMBG contains a character that is not a digit: " + c);
}
public static void main(String[] args) {
String[] examples = {"0101010710001", "12345", "01010107A0001"};
for (String j : examples) {
try {
check(j);
System.out.println(j + ": correct form");
} catch (InvalidIdNumberException e) {
System.out.println(j + ": " + e.getMessage());
}
}
}
}
Output:
0101010710001: correct form
12345: The JMBG must have 13 digits, but it has 5
01010107A0001: The JMBG contains a character that is not a digit: A
Practice tasks
Each task has an example, a hint and a solution. The solutions have been checked on the examples in the text.
TASK 01Difficulty: easy
The sum of the valid ones
Read n, then n words. Some of them are whole numbers and some are not. Print the sum of all the words that are whole numbers and, on the second line, the number of invalid ones.
Example
Input
6
12 abc 5 -3 7x 100
Output
114
2
Hint
For each word try Integer.parseInt in a try block; in catch (NumberFormatException e) increase the counter of invalid words.
Solution (Java)
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
long sum = 0;
int invalid = 0;
for (int i = 0; i < n; i++) {
String s = sc.next();
try {
sum += Integer.parseInt(s);
} catch (NumberFormatException e) {
invalid++;
}
}
System.out.println(sum);
System.out.println(invalid);
}
}
TASK 02Difficulty: medium
A calculator
Each line of input has the form a op b, where op is one of + - * /. For each line print the result of the integer operation or a message: ERROR: division by zero, ERROR: not a number or ERROR: unknown operation. The first line contains the number of expressions n.
Example
Input
5
7 + 5
9 / 0
8 * x
20 / 3
4 ^ 2
Output
12
ERROR: division by zero
ERROR: not a number
6
ERROR: unknown operation
Hint
Write a method calculate(int a, String op, int b) that throws IllegalArgumentException for an unknown operation. In main catch three kinds of exceptions.
Solution (Java)
import java.util.Scanner;
public class Main {
static int calculate(int a, String op, int b) {
switch (op) {
case "+": return a + b;
case "-": return a - b;
case "*": return a * b;
case "/": return a / b; // for b == 0 it throws ArithmeticException
default: throw new IllegalArgumentException("unknown operation");
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
for (int i = 0; i < n; i++) {
String a = sc.next(), op = sc.next(), b = sc.next();
try {
System.out.println(calculate(Integer.parseInt(a), op, Integer.parseInt(b)));
} catch (NumberFormatException e) {
System.out.println("ERROR: not a number");
} catch (ArithmeticException e) {
System.out.println("ERROR: division by zero");
} catch (IllegalArgumentException e) {
System.out.println("ERROR: " + e.getMessage());
}
}
}
}
Common mistakes and tips
Do not catch all exceptions with an empty block catch (Exception e) { } – the error is then "swallowed" and hard to find.
The order of catch blocks: a more specific exception before a more general one (e.g. NumberFormatException before IllegalArgumentException), otherwise the program will not compile.
Exceptions are not a replacement for ordinary checks: if you can check if (b != 0), do it.
Read the message and the line number in the stack trace before you change the code.
Check your knowledge
Open the quiz
Exceptions
1. What happens to an exception that nobody catches?
2. When is the finally block run?
3. Which exception does Integer.parseInt("12a") throw?
4. What is the word throws in a method header used for?
Podešavanja kolačića
Koristimo kolačiće da bismo vam pružili najbolje moguće iskustvo. Takođe nam omogućavaju da analiziramo ponašanje korisnika kako bismo stalno poboljšavali veb lokaciju za vas.