Introduction to python errors, exceptions and program debugging methods (with code)

不言
Release: 2019-04-11 11:59:14
forward
3279 people have browsed it

This article brings you an introduction to python errors, exceptions and program debugging methods (with code). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Exceptions are errors caused by Python programs during running. If an unhandled exception is thrown in the program, the program will terminate due to the exception. Only by adding exception handling to the program can the program be more " robust".

Python has its own grammatical form for handling exceptions. Master how to handle exceptions and program debugging in Python. The main contents are:

  • List items
  • List items
  • Syntax errors;
  • The concept of exceptions;
  • Use try statements to capture exceptions;
  • Handling of common exceptions;
  • Custom exception;
  • Use pdb to debug Python programs.

7.1 Syntax error

1. Spelling errors

refer to misspelling of keywords in the Python language, misspelling of variable names, function names, etc.

If the keyword is spelled incorrectly, a SyntaxError (syntax error) will be prompted, and if the variable name or function name is spelled incorrectly, a NameError error will be prompted at runtime.

2. The script program does not comply with Python's syntax specifications

For example, there are missing brackets, colons and other symbols, and expressions are written incorrectly.

3. Indentation error

Because Python grammar stipulates that indentation is one of the program's grammar, which should be a unique aspect of the Python language. Generally speaking, Python's standard indentation is 4 spaces. Of course, you can use Tab according to your own habits. However, the same indentation style should be used consistently in the same program or project.

7.2 Exception handling

Exceptions are errors caused by Python programs during running. If an unhandled exception is thrown in the program, the script will terminate due to the exception. Only by catching these exceptions in the program and performing relevant processing can the program not be interrupted.

7.2.1 Basic syntax for exception handling

The try statement is used in Python to handle exceptions. Like other statements in Python, the try statement also uses an indentation structure. The try statement also has an optional Selected else statement block. The basic form of a general try statement is as follows.

try:
     <语句(块)>            #可能产生异常的语句(块)
  except <异常名1>:          #要处理的异常
     <语句(块)>            #异常处理语句
  except <异常名2>:          #要处理的异常
     <语句(块)>            #异常处理语句
  else:
     <语句(块)>            #未触发异常,则执行该语句(块)
  finally:
     <语句(块)>            #始终执行该语,一般为了达到释放资源等目的
  
Copy after login

In actual applications, some statements can be used according to the needs of the program. Common forms are:

Form 1:

try:
     <语句(块)>
  except <异常名1>:
     <语句(块)>
  
Copy after login

Example:

def testTry (index, flag=False):
     stulst = ["John","Jenny","Tom"]
     if flag:                         #flag为True时,捕获异常
        try:
           astu = stulst [index]
        except IndexError:
           print("IndexError")
        return "Try Test Finished!"
     else:                            #flag为False时,不捕获异常
        astu =stulst [index]
        return "No Try Test Finished!"
  print("Right params testing start...")
  print (testTry (1, True))           #不越界参数,捕获异常(正常)
  print (testTry (1, False))          #不越界参数,不捕获异常(正常)
  print("Error params testing start...")
  print (testTry (4, True))           #越界参数,捕获异常(正常)
  print (testTry (4, False))          #越界参数,不捕获异常(程序运行会中断)
  
Copy after login

Form 2:

 try:
        <语句(块)>
     except < 异常名1>:
        <语句(块)>
     finally:
        <语句(块)>
 
Copy after login

Example:

def testTryFinally (index):
     stulst = ["John","Jenny", "Tom"]
     af = open ("my.txt", 'wt+')
     try:
        af.write(stulst[index])
     except:
        pass
     finally:
        af.close()               #无论是否产生越界异常,都关闭文件
        print("File already had been closed!")
  print('No IndexError...')
  testTryFinally (1)             #无越界异常,正常关闭文件
  print('IndexError...')
  testTryFinally (4)             #有越界异常,正常关闭文件
Copy after login
7.2.2 Python's main built-in exceptions and their handling

Common exceptions in Python have been predefined. In an interactive environment, using the dir (__builtins__) command will display all predefined exceptions.

##AttributeErrorCall Exception raised by non-existent methodEOFErrorException raised by encountering the end of fileImportErrorException caused by import module errorIndexErrorException caused by list out of boundsIOErrorExceptions caused by I/O operations, such as errors in opening files, etc.KeyErrorExceptions caused by using keywords that do not exist in the dictionaryNameErrorException caused by using a non-existent variable nameTabErrorException caused by incorrect statement block indentation ValueErrorException raised by a value that does not exist in the search listZeropisionErrorThe divisor is Exception raised by zero

except语句主要有以下几种用法

except:                              #捕获所有异常;
except <异常名>:                      #捕获指定异常;
except (异常名1,异常名2):            #捕获异常名1或者异常名2;
except <异常名> as <数据>:            #捕获指定异常及其附加的数据;
except(异常名1,异常名2)as <数据>:  #捕获异常名1或者异常名2及异常的附加数据。
Copy after login

7.3 手工抛出异常

为了程序的需要,程序员还可以自定义新的异常类型,例如对用户输入文本的长度有要求,则可以使用raise引发异常,以确保文本输入的长度符合要求。

7.3.1 用raise手工抛出异常

使用raise引发异常十分简单,raise有以下几种使用方式。

  raise 异常名
  raise 异常名,附加数据
  raise 类名
使用raise可以抛出各种预定的异常,即使程序在运行时根本不会引发该异常。

def testRaise2():
        for i in range (5):
             try:
                if i==2:    #i==2抛出NameError异常
                  raise NameError
             except NameError:
                print('Raise a NameError!')
             print (i)
        print('end...')

testRaise2 ()
Copy after login

运行结果:

0
1
Raise a NameError!
2
3
4
end...
Copy after login

7.3.2 assert语句

assert语句的一般形式如下。

assert <条件测试>, <异常附加数据>           #其中异常附加数据是可选的
Copy after login

assert语句是简化的raise语句,它引发异常的前提是其后面的条件测试为假。

举例:

def testAssert():
     for i in range (3):
        try:
           assert i<2
        except AssertionError:
           print('Raise a AssertionError!')
        print (i)
     print('end...')

  testAssert()
Copy after login

运行结果:

0
1
Raise a AssertionError!
2
end...
Copy after login

assert语句一般用于在程序开发时测试代码的有效性。比如某个变量的值必须在一定范围内,而运行时得到的值不符合要求,则引发该异常,对开发者予以提示。所以一般在程序开发中,不去捕获这个异常,而是让它中断程序。原因是程序中已经出现了问题,不应继续运行。

assert语句并不是总是运行的,只有Python内置的一个特殊变量__debug__为True时才运行。要关闭程序中的assert语句就使用python-O(短画线,后接大写字母O)来运行程序。

7.3.3 自定义异常类

在Python中定义异常类不用从基础完全自己定义,只要通过继承Exception类来创建自己的异常类。异常类的定义和其他类没有区别,最简单的自定义异常类甚至可以只继承Exception类,类体为pass如:

class MyError (Exception):          #继承Exception类
     pass
Copy after login

如果需要异常类带有一定的提示信息,也可以重载__init__和__str__这两个方法。【相关推荐:python视频教程

Exception nameDescription

The above is the detailed content of Introduction to python errors, exceptions and program debugging methods (with code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact [email protected]
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!