PythonTryCatch异常教程
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 other a then a number we will get an exception.
当我们调⽤的应⽤程序像下⾯通过提供像其他字符a接着⼀个号码,我们会得到⼀个异常。
$ python3 myapp.py
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 it() function.
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异常。
了解更多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 mechanism try which is used to detect exceptions in the given block of the code. We will put the potential error block into like try below. Here we guess
that line print(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 it a will not raise an exception. It simply skips to the code except block which will run if an exception is raised. Then the application will flow in a normal situation.
当我们通过提供个性像它运⾏a不会引发异常。 它只是跳到except块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 code except block. But we can catch a specific type of exception and ignoring others. As we remember from the first example we get the exception TypeError. If we only need to catch an exception TypeError and ignore others we will specify to TypeError the like except below.
在前⾯的⽰例中,我们使⽤代码except块触发了⼀种异常类型。 但是我们可以捕获特定类型的异常并忽略其他异常。 我们记得在第⼀个⽰例中,我们得到了TypeError 。 如果我们只需要捕获TypeError并忽略其他异常,我们将为TypeError指定以下内容, except下⾯的内容。
python的try和except用法#!/usr/bin/python3
num1 = input ("Enter number")
try:
print(num1*num1)
except TypeError:
print("An TypeError occurred")
print("Operation completed")
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 .
在此⽰例中,我们将捕获TypeError和ZeroDivisionError 。
#!/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代码块中使⽤的还原操作。
了解更多Apache⽇志⽂件
In this example, we will close file-handle in the finally code block whether previous code blocks work or raise an exception.
在此⽰例中,我们将关闭finally代码块中的⽂件句柄,⽽不管先前的代码块是否起作⽤或引发异常。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。