Talking about Exception in Python

本文详细介绍了Python中的异常处理机制,包括异常的定义、如何引发异常、自定义异常类、捕获异常、处理异常的方式,如`try/except`语句的使用,以及如何优雅地处理异常。此外,还讲解了`finally`子句用于确保清理工作,以及异常在函数调用中的传播方式。通过示例代码展示了如何避免和处理`ZeroDivisionError`、`TypeError`等常见异常,并讨论了使用警告来提醒非严重问题的方法。
摘要由CSDN通过智能技术生成

What is Exception

In fact Python will report exception when it meet error. if error is not been deal with, the

program will terminate and display a error message(traceback):

>>> 1 / 0 
Traceback (most recent call last): 
 File "<stdin>", line 1, in ? 
ZeroDivisionError: integer division or modulo by zero 

every exception is a living example of class named ‘ZeroDivisionError’.

In fact we can learn how to make exception first, and then we will learn how to deal with these exception then.

Raise statement

if you want to make exception , you can use raise statement. and make a class(must sub class of Exception) or living example (instantiation) as argument. when you use class as argument, it will create a instantiation . the example next is using inter exception class named “Exception”:

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 

In the first example(raise Exception), cause a general exception, which doesn’t point out what exception it caused. In the second example, and a error message “hyperdrive overload”

there are many inter exception class. all these classes can be used in the raise statement:

raise ArithmeticError 
Traceback (most recent call last): 
 File "<stdin>", line 1, in ? 
ArithmeticError 
name of classes description
Exception almost all the exception classes are derived from it
AttributeError cause when quote property or when assign value
OSError cause when operate system can’t deal with pointed assignment(such as when search file),more than one class
IndexError cause when want to use index which not exist. sub class of LookupError
KeyError cause when want to use key which not exist. sub class of LookupError
NameError cause when can’t find name of variable
SyntaxError cause when some code block is wrong
TypeError cause when some internal operate or function used for wrong type
ValueError cause when some internal operate or function used for object: right type but value wrong
ZeroDivisionError cause when second variable is 0 in devision

Self-defining exception class

If you want to use specific method to deal with specific error, you have to use a self-defining exception class:

how to create a exception class? like create other class, you should inherit directly or indirectly (this means that you can inherit from any internal exception class) so, the code block which creat a self-defining exception class like this :

class SomeCustomException(Exception): pass 

it is not difficult (of cause if you want, you can add method in the class).

Catch exception

usually we can deal with the exception and this operation named “catch exception”.

To make this , we can use try/except statement. Assume that you create a program, let user input two number, than make devision. like this :

x = int(input('Enter the first number: ')) 
y = int(input('Enter the second number: ')) 
print(x / y) 

the program runs well, while the user input 0 as the second number:

Enter the first number: 10 
Enter the second number: 0 
Traceback (most recent call last): 
 File "exceptions.py", line 3, in ? 
 print(x / y) 
ZeroDivisionError: integer division or modulo by zero 

to catch this exception and deal with the error (print a better message for user), we can rewrite the program like this:

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!") 

notice: the exception is broadcast from function to the call function . if not be catch in call function, it will broadcast to top. this means that you can use try/except statement to catch exception created by other people.


Not have to provide arguments

after catching exception, if you want to call it. you can call ‘raise’ statement without argument(of cause you can explicit provide exception catch).

it is very useful, let’s see a calculate class which can restrain exception “ZeroDivisionError”, if we use this usage, the calculator will print a wrong message, not spread the exception. when user use this calculator, it is useful to restrain exception; but when using internal function, spread exception is better way(this time we have not to use the usage), next is a code of class like this :

class MuffledCalculator: 
 muffled = False 
 def calc(self, expr): 
 try: 
 return eval(expr) 
 except ZeroDivisionError: 
 if self.muffled: 
 print('Division by zero is illegal') 
 else: 
 raise 

notice: When we divide 0(as second number), if we use ‘restrain’ usage, the method ’ calc ’ will return None. In other word, if we restrain the exception, we should not depend on the return value.


The example below displays usage of this class(includes the on and off restrain usage):


                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值