Python Try Catch异常教程

As a developer, we have a lot of thoughts about the applications and features. Implementing them a tedious task. During the implementation, we can make mistakes. Those mistakes can be related to applications logic or technical. These errors will cause problems while the application is running. We call this type of problem as exceptions. We can not prevent all exceptions but we can create some mechanisms to handle these situations. In this tutorial, we will look at how to handle these exceptions.

作为开发人员,我们对应用程序和功能有很多想法。 实施它们是一项繁琐的任务。 在实施过程中,我们可能会犯错误。 这些错误可能与应用程序逻辑或技术有关。 这些错误将在应用程序运行时引起问题。 我们称这类问题为例外。 我们无法防止所有异常,但可以创建一些机制来处理这些情况。 在本教程中,我们将研究如何处理这些异常。

什么是例外 (What is An Exception)

Some of us may be familiar with exceptions but there may be others who do not have any idea about exceptions. Exceptions are unexpected error situations where applications generally stop working. Sometimes it will not stop working but will not work properly either.

我们中的有些人可能对异常很熟悉,但有些人可能对异常一无所知。 异常是应用程序通常停止运行的意外错误情况。 有时它不会停止工作,但也不能正常工作。

Here is an example of how an exception occurs. Our applications get input from the user and multiple given numbers. But there will be an exception if the user inputs string. The filename is myapp.py .

这是一个异常发生情况的示例。 我们的应用程序从用户和多个给定的数字中获取输入。 但是,如果用户输入字符串,则会出现异常。 文件名是myapp.py

#!/usr/bin/python3 
 
num1 = input ("Enter number") 
 
print(num1*num1)

When we call our application like below by providing a character like othera then a number we will get an exception.

当我们调用的应用程序像下面通过提供像其他字符a接着一个号码,我们会得到一个异常。

$ python3 myapp.py
What is An Exception
What is An Exception
什么是例外

We also get the exception type. Python provides a different type of exceptions for different situations. In this code the exception type is TypeError .

我们还获得了异常类型。 Python针对不同情况提供了不同类型的异常。 在此代码中,异常类型为TypeError

异常类型 (Exception Types)

As there are a lot of different libraries and function there is a different type of exceptions. Here some of the most popular of them.

由于存在许多不同的库和函数,因此存在不同类型的异常。 在这里,其中一些最受欢迎。

  • Exception is the generic and base class for all exceptions.

    Exception是所有异常的通用和基类。

  • StopIteration exception raised when the next() method of an iterator does not point to any object.

    当迭代器的next()方法未指向任何对象时,引发StopIteration异常。

  • SystemExit exception raised by the sys.exit() function.

    sys.exit()函数引发的SystemExit异常。

  • StandardError is a base class and exception for all built-in exceptions except StopIteration and SystemExit.

    StandardError是除StopIteration和SystemExit之外的所有内置异常的基类和异常。

  • ArithmeticError is a base class for all error that occurs during mathematical and arithmetic calculations and operators.

    ArithmeticError是所有在数学和算术计算以及运算符期间发生的错误的基类。

  • OverFlowError exception raised when calculation exceeds the maximum limit for given numerical type.

    当计算超出给定数值类型的最大限制时引发OverFlowError异常。

  • ZeroDivisionError exception raised when a division or modulo by zero takes place for numerical operations.

    在对数字运算进行除数或以零为模时引发ZeroDivisionError异常。

  • AssertionError raised in case of failure of the assert Python programming language statement.

    在断言Python编程语言语句失败的情况下引发AssertionError

  • AttributeError exception raised in case of failure of attribute reference or assignment.

    在属性引用或分配失败的情况下引发AttributeError异常。

  • EOFError exception raised when there is no input or the end of a file is reached.

    没有输入或到达文件末尾时EOFError异常。

  • ImportError exception raised when an import Python programming language statement fails.

    导入Python编程语言语句失败时引发ImportError异常。

  • KeyboardInterrupt exception raised when the user interrupts the execution of the application with Linux kill command or pressing CTRL+C keyboard shortcut.

    当用户使用Linux kill命令或按CTRL + C键盘快捷键中断应用程序的执行时,将引发KeyboardInterrupt异常。

  • LookupError exception raised for all lookup errors.

    针对所有查找错误引发LookupError异常。

  • IndexError exception raised when an index is not found in the array, list in a sequence.

    当在数组中找不到索引时,引发序列错误IndexError异常。

  • KeyError exception raised when the specified key is not found in the dictionary.

    在字典中找不到指定的键时引发KeyError异常。

  • NameError exception raised when an identifier is not found in the local or global namespace.

    在本地或全局名称空间中找不到标识符时引发NameError异常。

  • UnboundLocalError exception raised when trying to access a local variable in a function, method, module but no value has been assigned to it.

    尝试访问函数,方法,模块中的局部变量但未分配任何值时引发了UnboundLocalError异常。

  • EnvironmentError is based class for all exceptions that occur outside of the Python Environment.

    EnvironmentError是Python环境外部发生的所有异常的基类。

  • IOError exception raised when an input/output operations fail, such as writing a file failed or a file can not be opened.

    当输入/输出操作失败(例如,写入文件失败或无法打开文件)时, IOError异常。

  • SyntaxError exception raised when there is an error related to the Python Syntax.

    与Python语法相关的错误时引发SyntaxError异常。

  • IndentationError exception raised when indentation is not specified and used properly to catch code block.

    未指定缩进并正确用于捕获代码块时引发IndentationError异常。

  • SystemError exception raised when the Python interpreter finds and, internal problem.

    当Python解释器发现and内部问题时,引发SystemError异常。

  • TypeError exception raised when an operation, function, method is attempted to get, set different type of variable or data type.

    尝试获取操作,函数,方法,设置不同类型的变量或数据类型时TypeError异常。

  • ValueError exception raised when built-in function fora data type has the valid type of arguments, but the arguments have invalid values.

    当数据类型的内置函数具有有效类型的参数,但参数具有无效值时,引发ValueError异常。

  • RuntimeError exception raised when the raised exception or error does not suit any specific category.

    当引发的异常或错误不适合任何特定类别时,引发RuntimeError异常。

  • NotImplementedError exception raised when an abstract method that is not implemented tried to be used.

    尝试使用未实现的抽象方法时引发NotImplementedError异常。

LEARN MORE  Linux "Command Not Found" Error And Solution
了解更多Linux“找不到命令”错误和解决方案

使用try和Except捕获异常(Catch An Exception with Try and Except)

Now we want to prevent this type of bugs and exceptions programmatically. Python provides a mechanismtry which is used to detect exceptions in the given block of the code. We will put the potential error block into liketry below. Here we guess that lineprint(num1-num1) can raise an exception.

现在,我们要以编程方式防止此类错误和异常。 Python提供了一种机制try ,用于检测给定代码块中的异常。 我们将潜在的错误块放入下面的try中。 在这里,我们猜测行print(num1-num1)会引发异常。

#!/usr/bin/python3 
 
num1 = input ("Enter number") 
 
try: 
   print(num1*num1) 
 
except: 
   print("An error occured") 
    
 
print("Operation completed")

When we run by providing a character like ita will not raise an exception. It simply skips to the codeexcept block which will run if an exception is raised. Then the application will flow in a normal situation.

当我们通过提供个性像它运行a不会引发异常。 它只是跳到exceptexcept的代码,如果引发异常,该块将运行。 然后,应用程序将在正常情况下运行。

Handle An Exception with Try and Except
Handle An Exception with Try and Except
使用try和Except处理异常

捕获特定异常(Catching Specific Exceptions)

In the previous example, we have fired a single type of exception with the codeexcept block. But we can catch a specific type of exception and ignoring others. As we remember from the first example we get the exceptionTypeError. If we only need to catch an exceptionTypeError and ignore others we will specify toTypeError the likeexcept below.

在前面的示例中,我们使用代码except块触发了一种异常类型。 但是我们可以捕获特定类型的异常并忽略其他异常。 我们记得在第一个示例中,我们得到了TypeError 。 如果我们只需要捕获TypeError并忽略其他异常,我们将为TypeError指定以下内容, except下面的内容。

#!/usr/bin/python3 
 
num1 = input ("Enter number") 
 
try: 
   print(num1*num1) 
 
except TypeError: 
   print("An TypeError occurred") 
 
 
print("Operation completed")
Catching Specific Exceptions
Catching Specific Exceptions
捕获特定异常

否则,如果未引发异常(Else If No Exception Raised)

We generally expect to raise some exception while running critical code. But in some cases, there will be no error or exception. We can define some code to execute if there is no error and exception to the else keyword. We will put the code we want to run if there is no error or exception inside else keyword block. In this example, we will print the screen “There is no exception” if there is no error or exception.

我们通常希望在运行关键代码时引发一些异常。 但是在某些情况下,不会有错误或异常。 如果else关键字没有错误和异常,我们可以定义一些要执行的代码。 如果else关键字块中没有错误或异常,我们将放置我们要运行的代码。 在此示例中,如果没有错误或异常,我们将打印“无异常”屏幕。

#!/usr/bin/python3 

num1 = input ("Enter number") 

try:   print(num1*num1) 

except TypeError:   
   print("An TypeError occurred") 

else: 
   print("There is no exception")

print("Operation completed")

捕获多个类型异常 (Catch Multiple Type Exceptions)

We may need to catch multiple exceptions in a single except code block. We will provide the exception types in brackets by separating them with command (TypeA , TypeB , TypeC , ...)

我们可能需要赶在一个多例外except代码块。 我们将在括号中提供例外类型,方法是使用命令将它们分开(TypeA , TypeB , TypeC , ...)

In this example we will catch both TypeError and ZeroDivisionError .

在此示例中,我们将捕获TypeErrorZeroDivisionError

#!/usr/bin/python3 
 
num1 = input ("Enter number") 
 
try: 
   print(num1*num1) 
 
except (TypeError,ZeroDivisionError): 
   print("An TypeError occured") 
 
 
print("Operation completed")

最终后在异常后运行代码 (Run Code After Exception with Finally)

While checking exceptions in try code block we may need to execute some come whatever happens even try code block works or except code block works. We will use finally code block to complete the try-except blocks. After the try-except blocks finally, the code block will be run. This is generally used to release resources like file, database connection, or revert operations used in try code block.

在检查try代码块中的异常时,我们可能需要执行一些意外的事情,即使try代码块工作或除代码块工作之外。 我们将使用finally代码块完成try-except块。 最后,在try-except块之后,将运行代码块。 通常用于释放资源,如文件,数据库连接或try代码块中使用的还原操作。

LEARN MORE  Apache Log Files
了解更多Apache日志文件

In this example, we will close file-handle in the finally code block whether previous code blocks work or raise an exception.

在此示例中,我们将关闭finally代码块中的文件句柄,而不管先前的代码块是否起作用或引发异常。

#!/usr/bin/python3 
 
try: 
   f = open("personels.txt") 
   f.read() 
 
finally: 
   f.close()

引发异常 (Raise Exception)

Up to now, we have handled self-raised exceptions. We can also raise an exception manually without waiting for a user to input any change. We will use keywordraise in order to raise an exception manually. In this example, we will raise typeZerrorDivisionError exception.

到目前为止,我们已经处理了自举异常。 我们还可以手动引发异常,而无需等待用户输入任何更改。 我们将使用关键字raise以手动引发异常。 在此示例中,我们将引发ZerrorDivisionError类型的异常。

#!/usr/bin/python3 
 
try: 
   print("0/0") 
   raise ZeroDivisionError 
 
except (ZeroDivisionError): 
   print("An ZeroDivisionError occurred") 
 
 
print("Operation completed")
Raise Exception
Raise Exception
引发异常

用户定义的异常(User-Defined Exceptions)

While programming enterprise applications and libraries we will need to create our exception type library too. We may need to provide operational exceptions like invalid move operations for files. We can define our own user-defined exceptions by using classRuntimeError like below. We will put the following code into CorpExceptions.py

在对企业应用程序和库进行编程时,我们也需要创建异常类型库。 我们可能需要提供操作异常,例如文件的无效移动操作。 我们可以使用如下所示的类RuntimeError来定义自己的用户定义的异常。 我们将以下代码放入CorpExceptions.py

#!/usr/bin/python3 
 
class InvalidMove(RuntimeError): 
   def __init__(self, arg): 
      self.args = arg

and we can raise as we did before after importing CorpExceptions.py

在导入CorpExceptions.py之后,我们可以像以前一样提高

raise InvalidMode

翻译自: https://www.poftut.com/python-try-catch-exceptions-tutorial/

  • 5
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值