Lesson 6.3
What an exception is
Part 6: Errors, testing and filesReading, about 6 min1 exercise in this lesson
What an exception is
By the end of this you will be able to say what an exception is, read the message a program shows when one stops it, name the common ones in your language, and say when a program should deal with one.
A run-time error has a name
In lesson 6.1 you met run-time errors, such as turning text like three into a whole number: a line that cannot be carried out with the values it has. When that happens, the language does not just give up. It makes an exception: a report of what went wrong, with a name for the kind of problem and a message with the details.
In Python, the line is said to raise the exception. In Java, it throws it. Both words mean the same thing here.
If nothing in the program deals with the exception, the program stops at that line and shows the report. Every line before it has already run. No line after it runs.
This program is meant to work out the cost of some tickets at 5 dollars each, but the number of tickets has been written as a word.
text = "two"
print("Asked: " + text)
count = int(text)
print(count * 5)public static void main(String[] args) {
String text = "two";
System.out.println("Asked: " + text);
int count = Integer.parseInt(text);
System.out.println(count * 5);
}The first print line runs, so this appears:
Asked: two
Then the conversion fails, the program stops, and the last line never runs.
Reading the report
When code stops on this site (Java runs here later), the result names the line that stopped, then gives the name of the exception, a colon, and the message. For this program the name and message are ValueError: invalid literal for int() with base 10: 'two' in Python, and NumberFormatException: For input string: "two" in Java.
If you run a program on your own computer, the report is longer, but the same three things are in it.
- In Python, the report starts with
Traceback (most recent call last):, then names the line where the exception happened, with its line number. The name and the message are on the last line of the report. - In Java, the name and the message are on the first line, after
Exception in thread "main", and, for the exceptions in this lesson, the name starts withjava.lang., as injava.lang.NumberFormatException. Below it are lines that start withat. Most of them are inside Java itself. The one that names your own file, such asMain.java:5, gives your line number, here line 5.
So in each language, read three things: the name, the message, and the line number in your code.
The ones you will meet most
Each kind of problem has its own exception, so the name tells you what went wrong before you read anything else. In this list, every Java name ends in Exception, and every Python name ends in Error.
- Text that is not a whole number, turned into one:
ValueErrorin Python,NumberFormatExceptionin Java. - A whole number divided by the whole number 0:
ZeroDivisionErrorin Python,ArithmeticExceptionin Java. - An index past the end of a list:
IndexErrorin Python. In Java,ArrayIndexOutOfBoundsExceptionfor an array, andIndexOutOfBoundsExceptionfor anArrayList. - One character asked for at a position past the end of a text:
IndexErrorin Python,StringIndexOutOfBoundsExceptionin Java.
There is one difference to watch for with division. In Java, only whole-number division by 0 throws. A double divided by 0 gives no exception: 7.0 / 0 gives Infinity. In Python, dividing any number by 0 raises a ZeroDivisionError.
An exception is not a syntax error
An exception can only happen while the program is running, at one line, with the values that line has at that moment. With other values, the same line might run with no problem at all.
A syntax error is different: it is found before any of the program runs, and nothing runs at all. (In Python, the report of a syntax error does carry an exception's name, SyntaxError. It still comes before any line of your program runs, so the program never gets the chance to deal with it.)
When should a program deal with one?
Ask where the problem came from.
- From outside the program: what the user types, or, later in the course, a file that is missing. The program cannot stop a user typing
twowhen it asks for a number of tickets. So the program should expect the exception and deal with it, instead of letting it stop everything. The next lesson shows how. - From a mistake in the code: a loop that runs one step too far and asks for an index that is not there. Here the right answer is to fix the code. Catching the exception would only hide the bug.
Two common mistakes
- Reading only the first line of a Python report on your own computer. There, the name and the message are on the last line.
- Thinking an exception means the code is badly written. Often the code is fine, and the problem is a value from outside, which the program should expect and deal with.
Now try it yourself on the questions below.
Exercise 6.3.16.3.1 · Answer itException age
A program asks the user for their age and converts what they type into a whole number. Explain what an exception is, using this program as your example, and why the program should catch it rather than stop. [2]