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

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
主站蜘蛛池模板: 鄱阳县| 翁牛特旗| 晋宁县| 丹江口市| 莫力| 花莲市| 津南区| 遵化市| 浦江县| 西丰县| 武乡县| 疏勒县| 昌平区| 融水| 华蓥市| 偃师市| 库伦旗| 盈江县| 松潘县| 柘荣县| 二连浩特市| 依安县| 西吉县| 梅河口市| 鄯善县| 五大连池市| 门头沟区| 台前县| 邻水| 固镇县| 绵竹市| 繁峙县| 郎溪县| 津市市| 阿图什市| 龙泉市| 瑞金市| 南宁市| 蒙自县| 清原| 二连浩特市|