An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.
When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits.
>>> 1 / 0
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ZeroDivisionError: integer division or modulo by zero
You can raise exceptions in several ways by using the raise statement. An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class.
>>> raise Exception
Traceback (most recent call last):
File "<stdin>", line 1, in ?
Exception
>>> raise Exception('hyperdrive overload')
Traceback (most recent call last):
File "<stdin>", line 1, in ?
Exception: hyperdrive overload
Build-in Exceptions:
Class Name | Description |
---|---|
Exception | The base class for almost all exceptions. |
AttributeError | Raised when attribute reference or assignment fails. |
OSError | Raised when the operating system can’t perform a task, such as a file, for example. Has several specific subclasses. |
IndexError | Raised when using a nonexistent index on a sequence. Subclass of LookupError. |
KeyError | Raised when using a nonexistent key on a mapping. Subclass of LookupError. |
NameError | Raised when a name (variable) is not found. |
SyntaxError | Raised when the code is ill-formed. |
TypeError | Raised when a built-in operation or function is applied to an object of the wrong type. |
ValueError | Raised when a built-in operation or function is applied to an object with the correct type but with an inappropriate value. |
ZeroDivisionError | Raised when the second argument of a division or modulo operation is zero. |
class SomeCustomException(Exception): pass
try:
x = int(input('Enter the first number: '))
y = int(input('Enter the second number: '))
print(x / y)
except ZeroDivisionError:
print("The second number can't be zero!")
More than one except clause
try:
x = int(input('Enter the first number: '))
y = int(input('Enter the second number: '))
print(x / y)
except ZeroDivisionError:
print("The second number can't be zero!")
except TypeError:
print("That wasn't a number, was it?")
Two exceptions with one block
try:
x = int(input('Enter the first number: '))
y = int(input('Enter the second number: '))
print(x / y)
except (ZeroDivisionError, TypeError, NameError):
print('Your numbers were bogus ...')
Printing error
try:
x = int(input('Enter the first number: '))
y = int(input('Enter the second number: '))
print(x / y)
except (ZeroDivisionError, TypeError) as e:
print(e)
Catching all
try:
x = int(input('Enter the first number: '))
y = int(input('Enter the second number: '))
print(x / y)
except:
print('Something wrong happened ...')
Catching all, done right
try:
x = int(input('Enter the first number: '))
y = int(input('Enter the second number: '))
print(x / y)
except Exception as e:
print('Something wrong happened: %s' % (e,))
Using else clause
try:
print('A simple task')
except:
print('What? Something went wrong?')
else:
print('Ah ... It went as planned.')
Using finally clause
x = None
try:
x = 1 / 0
finally:
print('Cleaning up ...')
del x
Combine it all
try:
1 / 0
except NameError:
print("Unknown variable")
else:
print("That went well!")
finally:
print("Cleaning up.")
{ "data": { "sessionMaterial": { "id": "session-material:2018/tieto:files-and-exceptions:1", "title": "Exceptions", "html": "\n \n \n\n <h2>Exceptions</h2>\n<p>An exception is an event, which occurs during the execution of a program that disrupts the normal flow of the program's instructions. In general, when a Python script encounters a situation that it cannot cope with, it raises an exception. An exception is a Python object that represents an error.</p>\n<p>When a Python script raises an exception, it must either handle the exception immediately otherwise it terminates and quits.</p>\n<div class=\"highlight\"><pre><code>>>> 1 / 0\nTraceback (most recent call last):\n File "<stdin>", line 1, in ?\nZeroDivisionError: integer division or modulo by zero</code></pre></div><h3>raise statement</h3>\n<p>You can raise exceptions in several ways by using the raise statement. An exception can be a string, a class or an object. Most of the exceptions that the Python core raises are classes, with an argument that is an instance of the class.</p>\n<div class=\"highlight\"><pre><code>>>> raise Exception\nTraceback (most recent call last):\n File "<stdin>", line 1, in ?\nException\n>>> raise Exception('hyperdrive overload')\nTraceback (most recent call last):\n File "<stdin>", line 1, in ?\nException: hyperdrive overload</code></pre></div><p>Build-in Exceptions:</p>\n<table>\n<thead><tr>\n<th>Class Name</th>\n<th>Description</th>\n</tr>\n</thead>\n<tbody>\n<tr>\n<td>Exception</td>\n<td>The base class for almost all exceptions.</td>\n</tr>\n<tr>\n<td>AttributeError</td>\n<td>Raised when attribute reference or assignment fails.</td>\n</tr>\n<tr>\n<td>OSError</td>\n<td>Raised when the operating system can’t perform a task, such as a file, for example. Has several specific subclasses.</td>\n</tr>\n<tr>\n<td>IndexError</td>\n<td>Raised when using a nonexistent index on a sequence. Subclass of LookupError.</td>\n</tr>\n<tr>\n<td>KeyError</td>\n<td>Raised when using a nonexistent key on a mapping. Subclass of LookupError.</td>\n</tr>\n<tr>\n<td>NameError</td>\n<td>Raised when a name (variable) is not found.</td>\n</tr>\n<tr>\n<td>SyntaxError</td>\n<td>Raised when the code is ill-formed.</td>\n</tr>\n<tr>\n<td>TypeError</td>\n<td>Raised when a built-in operation or function is applied to an object of the wrong type.</td>\n</tr>\n<tr>\n<td>ValueError</td>\n<td>Raised when a built-in operation or function is applied to an object with the correct type but with an inappropriate value.</td>\n</tr>\n<tr>\n<td>ZeroDivisionError</td>\n<td>Raised when the second argument of a division or modulo operation is zero.</td>\n</tr>\n</tbody>\n</table>\n<h3>Create custom exception class</h3>\n<div class=\"highlight\"><pre><code>class SomeCustomException(Exception): pass</code></pre></div><h3>Catching exceptions</h3>\n<div class=\"highlight\"><pre><code>try:\n x = int(input('Enter the first number: '))\n y = int(input('Enter the second number: '))\n print(x / y)\nexcept ZeroDivisionError:\n print("The second number can't be zero!")</code></pre></div><p><strong>More than one except clause</strong></p>\n<div class=\"highlight\"><pre><code>try:\n x = int(input('Enter the first number: '))\n y = int(input('Enter the second number: '))\n print(x / y)\nexcept ZeroDivisionError:\n print("The second number can't be zero!")\nexcept TypeError:\n print("That wasn't a number, was it?")</code></pre></div><p><strong>Two exceptions with one block</strong></p>\n<div class=\"highlight\"><pre><code>try:\n x = int(input('Enter the first number: '))\n y = int(input('Enter the second number: '))\n print(x / y)\nexcept (ZeroDivisionError, TypeError, NameError):\n print('Your numbers were bogus ...')</code></pre></div><p><strong>Printing error</strong></p>\n<div class=\"highlight\"><pre><code>try:\n x = int(input('Enter the first number: '))\n y = int(input('Enter the second number: '))\n print(x / y)\nexcept (ZeroDivisionError, TypeError) as e:\n print(e)</code></pre></div><p><strong>Catching all</strong></p>\n<div class=\"highlight\"><pre><code>try:\n x = int(input('Enter the first number: '))\n y = int(input('Enter the second number: '))\n print(x / y)\nexcept:\n print('Something wrong happened ...')</code></pre></div><p><strong>Catching all, done right</strong></p>\n<div class=\"highlight\"><pre><code>try:\n x = int(input('Enter the first number: '))\n y = int(input('Enter the second number: '))\n print(x / y)\nexcept Exception as e:\n print('Something wrong happened: %s' % (e,))</code></pre></div><p><strong>Using else clause</strong></p>\n<div class=\"highlight\"><pre><code>try:\n print('A simple task')\nexcept:\n print('What? Something went wrong?')\nelse:\n print('Ah ... It went as planned.')</code></pre></div><p><strong>Using finally clause</strong></p>\n<div class=\"highlight\"><pre><code>x = None\ntry:\n x = 1 / 0\nfinally:\n print('Cleaning up ...')\n del x</code></pre></div><p><strong>Combine it all</strong></p>\n<div class=\"highlight\"><pre><code>try:\n 1 / 0\nexcept NameError:\n print("Unknown variable")\nelse:\n print("That went well!")\nfinally:\n print("Cleaning up.")</code></pre></div>\n\n\n " } } }