Python for Programmers: Raising Exceptions
Welcome to the Raising Exceptions lesson!
This lesson is shown as static text below. However, it's designed to be used interactively. Click the button below to start!
When something goes wrong, Python indicates the error by raising ("throwing") an exception. Execution stops, and Python prints a message telling us what happened.
For example, invalid syntax raises an exception. (You can type
errorwhen a code example will cause an error.)>
sum = 2 +*/- 3Result:
SyntaxError: invalid syntax (<string>, line 1)
We can raise our own exceptions with a
raisestatement.raise SomeExceptionType(some_message)raises the provided exception. Most exceptions take one argument: a message describing what happened.In the next example, we raise
ValueError("Incorrect password").ValueErroris one of Python's many built-in exception types.>
provided_password = "hunter3"correct_password = "hunter2"if provided_password != correct_password:raise ValueError("Incorrect password")"Access granted"Result:
ValueError: Incorrect password
Exceptions are values, just like
12or"abc". Simply creating aValueErrordoesn't raise it, and it won't stop execution.>
provided_password = "hunter3"correct_password = "hunter2"if provided_password != correct_password:# Create an exception, but don't raise it. An easy mistake to make!ValueError("Incorrect password")"Access granted"Result:
'Access granted'
Python has a rich set of built-in exception types. Here are some examples:
TypeErrormeans that we provided data of the wrong type. For example, adding a number to a string raises aTypeErrorexception.>
"a" + 1Result:
TypeError: can only concatenate str (not "int") to str
ValueErrormeans that an argument had the correct type, but an incorrect value.>
my_number = 5if my_number % 2 != 0:raise ValueError("expected an even number")my_number / 2Result:
ValueError: expected an even number
ZeroDivisionErrormeans that we tried to divide by zero.>
5 / 0Result:
ZeroDivisionError: division by zero
There are many more built-in exception types. We won't go through all of them here, but several will show up throughout this course.
Python also has a generic exception type,
Exception.>
raise Exception("some generic error")Result:
Exception: some generic error
However, it's better to be specific when possible.
ValueErrormakes sense in many situations, since most errors are caused by an incorrect value of some kind.Later in the course, we'll define our own exception types. But we need to see many more Python features before we get there.
Finally, why does Python talk about "raising" exceptions, when most programming languages talk about "throwing" them? There's no deep reason behind it. It's just a difference in terminology, like Python having "lists" instead of "arrays".