Python Exception

本文详细介绍Python中的异常处理机制,包括单个及多个异常捕获、通用异常处理、带有参数的异常处理、finally子句的使用及自定义异常的抛出等核心概念。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1 处理exception:

try:

You do your operations here;
......................
except ExceptionI :
If there is ExceptionI, then execute this block.
except ExceptionII :
If there is ExceptionII, then execute this block.
......................
else:
If there is no exception then execute this block.

关键点:
  • A single try statement can have multiple except statements. This is useful when the try block contains statements that may throw different types of exceptions.

  • You can also provide a generic except clause, which handles any exception.

  • After the except clause(s), you can include an else-clause. The code in the else-block executes if the code in the try: block does not raise an exception.

  • The else-block is a good place for code that does not need the try: block's protection.

2 except后面没有exception
try:
You do your operations here;
......................
except:
If there is any exception, then execute this block.
......................
else:

不推荐,没有考虑root cause

3 except后面跟着多个exception

try:
You do your operations here;
......................
except(Exception1[, Exception2[,...ExceptionN]]]):
If there is any exception from the given exception list,
then execute this block.
......................
else:
If there is no exception then execute this block.

4 try --final

You can use a finally: block along with a try: block. The finally block is a place to put any code that must execute, whether the try-block raised an exception or not. The syntax of the try-finally statement is this:

try:

You do your operations here;
......................
Due to any exception, this may be skipped.
finally:
This would always be executed.
......................

Note that you can provide except clause(s), or a finally clause, but not both. You can not use else clause as well along with a finally clause.

5 exception带参数:


An exception can have an argument , which is a value that gives additional information about the problem. The contents of the argument vary by exception. You capture an exception's argument by supplying a variable in the except clause as follows:

try:
You do your operations here;
......................
except ExceptionType, Argument :
You can print value of Argument here...

If you are writing the code to handle a single exception, you can have a variable follow the name of the exception in the except statement. If you are trapping multiple exceptions, you can have a variable follow the tuple of the exception.

This variable will receive the value of the exception mostly containing the cause of the exception. The variable can receive a single value or multiple values in the form of a tuple. This tuple usually contains the error string, the error number, and an error location.

Example:

Following is an example for a single exception:

#!/usr/bin/python

# Define a function here.
def temp_convert(var):
try:
return int(var)
except ValueError, Argument:
print "The argument does not contain numbers/n", Argument

# Call above function here.
temp_convert("xyz");

This would produce following result:

The argument does not contain numbers invalid literal for int() with base 10: 'xyz'

 

6 raising an exception

 

raise [Exception [, args [, traceback]]]

Here Exception is the type of exception (for example, NameError) and argument is a value for the exception argument. The argument is optional; if not supplied, the exception argument is None.

The final argument, traceback, is also optional (and rarely used in practice), and, if present, is the traceback object used for the exception

Example:

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. Defining new exceptions is quite easy and can be done as follows:

def functionName( level ):
if level < 1:
raise "Invalid level!", level
# The code below to this would not be executed
# if we raise the exception

Note: In order to catch an exception, an "except" clause must refer to the same exception thrown either class object or simple string. For example to capture above exception we must write our except clause as follows:

try:
Business Logic here...
except "Invalid level!":
Exception handling here...
else:
Rest of the code here...

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

惹不起的程咬金

来都来了,不赏点银子么

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值