When something goes wrong mid-run
Some problems can't be detected until a program is running: a file that doesn't exist, a network that drops, a user typing "abc" where a number was expected. When code hits a situation like this, it can "raise" or "throw" an exception, a signal that stops normal execution and jumps to whatever code has offered to deal with it. If nothing handles the exception, the program stops and prints an error report.
A useful picture is a fire alarm. Once triggered, normal activity halts, and control goes to the people trained to respond. If nobody responds, the building is evacuated.
Catching one in Python
try:
age = int(input("Your age: "))
print("Next year you'll be", age + 1)
except ValueError:
print("Please enter a whole number.")
finally:
print("Done.")
If the input can't be converted, int() raises a ValueError, the except block runs, and the program carries on. The finally block runs either way. JavaScript, PHP, and Java use try/catch with the same idea.
Exceptions vs errors in general
Not every error is an exception you can handle. A syntax mistake, such as a missing bracket, usually stops the code from starting at all. (Python does have a SyntaxError class, but a try block can't catch a syntax error in the same file it sits in, because that file never gets to run.) Logic errors, where code runs but produces the wrong answer, raise nothing at all; you track those down by debugging.
Catch only the exceptions you know how to handle. A bare except: or empty catch block hides real problems and makes failures much harder to diagnose. Java goes further with "checked exceptions," which the compiler forces you to either handle or declare.
Exceptions happen at runtime, which is why they often depend on input data or the environment.
Learn more
Last updated