3. try-except语句的子句

try-except语句的子句

语法

try:
    可能引发异常的语句
except 异常类型1 [as 变量1]:
    异常处理语句1
except 异常类型2 [as 变量2]:
    异常处理语句2
...
except:
    异常处理语句other
else:
    未发生异常语句
finally:
    最终语句

说明:

示例

# try-except语句的子句示例

def sharing_apple(apple_count, person_count):
    ''' 将apple_count 个苹果分给 person_count 个人,并打印结果!'''
    try:
        person_count = int(person_count)  # 可能触发ValueError类型的错误
        result = apple_count / person_count  # 可能触发ZeroDivisionError和TypeError类型的错误
        print('每个人分', result, '个苹果',)
    except TypeError:
        print('类型错了,苹果数必须是数字')
    except ZeroDivisionError:
        print('人数为零,不能做除法')
    else:
        print('正常流程!')
    finally:
        print('我一定会被打印!')

# 调用分苹果函数
# sharing_apple(10, 2)  # 正常流程
# sharing_apple('10', 2)  # TypeError
# sharing_apple(10, 0)
sharing_apple(10, '2.5')
print('主模块中程序是正常状态')

print("程序正常执行并退出!")

上述示例中,else 子句会在try 内部没有引发异常是处理。

finally 子句在任何时候都一定会执行。

常见的异常类型

缩进代表继承关系。

BaseException
    Exception
        ArithmeticError
            ZeroDivisionError
        ImportError
            ModuleNotFoundError
        LookupError
            IndexError
            KeyError
        NameError
        ...
        OSError
            FileNotFoundError
        RuntimeError
            NotImplementedError
        StopIteration
        TypeError
        ValueError
    KeyboardInterrupt

Python 3.13 中全部的异常类型如下:

BaseException
    BaseExceptionGroup
        ExceptionGroup(BaseExceptionGroup, Exception)
    Exception
        ArithmeticError
            FloatingPointError
            OverflowError
            ZeroDivisionError
        AssertionError
        AttributeError
        BufferError
        EOFError
        ImportError
            ModuleNotFoundError
        LookupError
            IndexError
            KeyError
        MemoryError
        NameError
            UnboundLocalError
        OSError
            BlockingIOError
            ChildProcessError
            ConnectionError
                BrokenPipeError
                ConnectionAbortedError
                ConnectionRefusedError
                ConnectionResetError
            FileExistsError
            FileNotFoundError
            InterruptedError
            IsADirectoryError
            NotADirectoryError
            PermissionError
            ProcessLookupError
            TimeoutError
        ReferenceError
        RuntimeError
            NotImplementedError
            PythonFinalizationError
            RecursionError
        StopAsyncIteration
        StopIteration
        SyntaxError
            IndentationError
                TabError
        SystemError
        TypeError
        ValueError
            UnicodeError
                UnicodeDecodeError
                UnicodeEncodeError
                UnicodeTranslateError
        Warning
            BytesWarning
            DeprecationWarning
            EncodingWarning
            FutureWarning
            ImportWarning
            PendingDeprecationWarning
            ResourceWarning
            RuntimeWarning
            SyntaxWarning
            UnicodeWarning
            UserWarning
    GeneratorExit
    KeyboardInterrupt
    SystemExit

练习

写一个函数get_score() 来获取学生输入的成绩(0〜100的整数),如果输入出现异常,则此函数返回0,否则返回用户输入的成绩.