Contents
1. What is an exception?
- To
represent exceptional conditions
, Python usesexception objects
. When it encounters an error, it raises an exception. If such an exception object isnot handled (or caught)
, the programterminates
with a so-called traceback (an error message).
1/0
>>>
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-1-9e1622b385b6> in <module>()
----> 1 1/0
ZeroDivisionError: division by zero
Each exception object is an instance of some class( in this case the class is ZeroDivisionError)
, and these objects can be raised and handled by a lot of ways, allowing you to trap the error or perform some other actions about it instead of simply failing the program
.
2. The raise statement
- To raise an exception, you can use
raise
statement withan argument that either is a class( which should subclass Exception) or an instance(object)
.When using a class, the instance will be created automatically
. - raise Exception
raise Exception
>>>
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-4-2aee0157c87b> in <module>()
----> 1 raise Exception
Exception:
- raise Exception with message
raise Exception('This is an example exception')
>>>
---------------------------------------------------------------------------
Exception Traceback (most recent call last)
<ipython-input-5-588a592fb13b> in <module>()
----> 1 raise Exception('This is an example exception')
Exception: This is an example exception
- All the built-in Exceptions in the python library can be used in the raise statement.
3. Custom Exception Class
class SomeCustomException(Exception):
pass
4. Catch and handle the exception
try...except
:catch and handle the exception instead of failing the program,
try:
x=int(input('please input a number:'))
y=int(input('please input a number:'))
print(x/y)
except ZeroDivisionError:
print('<ZeroDivisionError!!>: the second number can not be zero')
>>>
please input a number:2
please input a number:0
<ZeroDivisionError!!>: the second number can not be zero
5. raise without arguments
If you have caught an exception and you want to raise it again, you can used raise statement without any argument
The following is a calculator with a switch for ZeroDivisionError. If the switch is turned on, the programm will print a message after catch the exceprtion. Otherwise, the programm will raise the exception again and fail.
class SwitchCalculator:
switch=False #switch off
def calc(self,exp):
try: # try statement inside the function(method)
return eval(exp)
except ZeroDivisionError:
if self.switch:# use the attributes of the class inside itself, use self.attribute
print('Division by zero is illegla')
else:
raise
sc=SwitchCalculator()
sc.calc('100/2')
>>>
50.0
sc.calc('100/0')# switch off
>>>
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-12-cda8db8202d4> in <module>()
----> 1 sc.calc('100/0')
<ipython-input-7-f0a94ea0989e> in calc(self, exp)
3 def calc(self,exp):
4 try:
----> 5 return eval(exp)
6 except ZeroDivisionError:
7 if self.switch:# use the attributes of the class inside itself, use self.attribute
<string> in <module>()
ZeroDivisionError: division by zero
sc.switch=True#switch on
sc.calc('100/0')
>>>
Division by zero is illegla
- try statement inside the function(method)
- use the attributes of the class inside methods, use self.attribute, outside the methods you can just use the name, like switch
6. raise another exception
try: # catch and raise
1/0
except ZeroDivisionError:
raise
>>>
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-22-21367911f8dd> in <module>()
1 try:
----> 2 1/0
3 except ZeroDivisionError:
4 raise
ZeroDivisionError: division by zero
try: #catch and raise another exception.
1/0
except ZeroDivisionError:
raise ValueError('Cannot be divided by zero') # an exception with message.
>>>
---------------------------------------------------------------------------
ZeroDivisionError Traceback (most recent call last)
<ipython-input-24-08ac2119fbfa> in <module>()
1 try:
----> 2 1/0
3 except ZeroDivisionError:
ZeroDivisionError: division by zero
During handling of the above exception, another exception occurred:
ValueError Traceback (most recent call last)
<ipython-input-24-08ac2119fbfa> in <module>()
2 1/0
3 except ZeroDivisionError:
----> 4 raise ValueError('Cannot be divided by zero')
ValueError: Cannot be divided by zero
The two exceptions’ information will all be presented
7. Catch more than one exception
try...except...except...
try:
x=int(input('Enter the first number:'))
y=int(input('Enter the second number:'))
print(x/y)
except ZeroDivisionError:
print('The second name cannot be zero!')
except ValueError:
print('This is not the right type!')
>>>
Enter the first number:3
Enter the second number:f
This is not the right type!
>>>
Enter the first number:1
Enter the second number:0
The second name cannot be zero!
8. Catch more exceptions with one block
try...except(exception1,exception2...)
try:
x=int(input('Enter the first number:'))
y=int(input('Enter the second number:'))
print(x/y)
except (ZeroDivisionError,ValueError):
print('There is something wrong with the number you enter!!!')
>>>
Enter the first number:a
There is something wrong with the number you enter!!!
>>>
Enter the first number:1
Enter the second number:0
There is something wrong with the number you enter!!!
9. Access the exception
If you want to access the exception object, you can use try... except...as...
try:
x=int(input('Enter the first number:'))
y=int(input('Enter the second number:'))
print(x/y)
except (ZeroDivisionError,ValueError) as e:
print(e)# access the exception object
>>>
Enter the first number:1
Enter the second number:0
division by zero
10. Catch all
If you want to catch some specific types of exceptions, use try… except (specificexceptions).
If you want to catch all exceptions, just use try… except.
try:
x=int(input('Enter the first number:'))
y=int(input('Enter the second number:'))
print(x/y)
except:
print('Something is wrong...')
>>>
Enter the first number:a
Something is wrong...
You can also use try...except Exception
try:
x=int(input('Enter the first number:'))
y=int(input('Enter the second number:'))
print(x/y)
except Exception:
print('Something is wrong...')
>>>
Enter the first number:a
Something is wrong...
11. try…except…else
while True:
try:
x=int(input('Please enter the first number:'))
y=int(input('Please enter the second number:'))
print(x/y)
except Exception as e:
print(e)
else:
break
>>>
Please enter the first number:a
invalid literal for int() with base 10: 'a'
Please enter the first number:1
Please enter the second number:0
division by zero
Please enter the first number:1
Please enter the second number:2
0.5
12. finally
finally
: in try statement, no matter what happened, the finally statement will be executed.
while True:
try:
x=int(input('Please enter the first number:'))
y=int(input('Please enter the second number:'))
print(x/y)
except Exception as e:
print(e)
else:
break
finally:
print('This is the last step of the program.')
>>>
Please enter the first number:5
Please enter the second number:0
division by zero
This is the last step of the program.
Please enter the first number:1
Please enter the second number:2
0.5
This is the last step of the program.