官术网_书友最值得收藏!

Error handling (exception handling)

In this section, we're going to learn how Python handles exceptions. But first, what is an exception? An exception is an error that occurs during program execution. Whenever any error occurs, Python generates an exception that will be handled using a try…except block. Some exceptions can't be handled by programs so they result in error messages. Now, we are going to see some exception examples.

In your Terminal, start the python3 interactive console and we will see some exception examples:

student@ubuntu:~$ python3
Python 3.5.2 (default, Nov 23 2017, 16:37:01)
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>>
>>> 50 / 0


Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ZeroDivisionError: division by zero
>>>
>>> 6 + abc*5
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'abc' is not defined
>>>
>>> 'abc' + 2
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'int' object to str implicitly
>>>
>>> import abcd
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ImportError: No module named 'abcd'
>>>

These are some examples of exceptions. Now, we will see how we can handle the exceptions.

Whenever errors occur in your Python program, exceptions are raised. We can also forcefully raise an exception using raise keyword.

Now we are going to see a try…except block that handles an exception. In the try block, we will write a code that may generate an exception. In the except block, we will write a solution for that exception.

The syntax for try…except is as follows:

try:
statement(s)
except:
statement(s)

A try block can have multiple except statements. We can handle specific exceptions also by entering the exception name after the except keyword. The syntax for handling a specific exception is as follows:

try:
statement(s)
except exception_name:
statement(s)

We are going to create an exception_example.py script to catch ZeroDivisionError. Write the following code in your script:

a = 35
b = 57
try:
c = a + b
print("The value of c is: ", c)
d = b / 0
print("The value of d is: ", d)

except:
print("Division by zero is not possible")

print("Out of try...except block")

Run the script as follows and you will get the following output:

student@ubuntu:~$ python3 exception_example.py
The value of c is: 92
Division by zero is not possible
Out of try...except block
主站蜘蛛池模板: 科技| 新宾| 彭水| 大城县| 石楼县| 罗源县| 贺兰县| 中方县| 顺义区| 青州市| 浦县| 体育| 南漳县| 区。| 定州市| 杭州市| 新化县| 道孚县| 邯郸县| 石狮市| 高淳县| 自治县| 平山县| 龙泉市| 松溪县| 万全县| 冕宁县| 南部县| 昭平县| 聊城市| 铁力市| 广河县| 大方县| 宁津县| 二手房| 海丰县| 炎陵县| 平湖市| 正定县| 临湘市| 瑞昌市|