search
HomeBackend DevelopmentPython TutorialIntroduction to python errors, exceptions and program debugging methods (with code)

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 :          #要处理的异常
                 #异常处理语句
  except :          #要处理的异常
                 #异常处理语句
  else:
                 #未触发异常,则执行该语句(块)
  finally:
                 #始终执行该语,一般为了达到释放资源等目的
  

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

Form 1:

try:
     
  except :
     
  

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))          #越界参数,不捕获异常(程序运行会中断)
  

Form 2:

 try:
        
     except :
        
     finally:
        
 

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)             #有越界异常,正常关闭文件
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及异常的附加数据。

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 ()

运行结果:

0
1
Raise a NameError!
2
3
4
end...

7.3.2 assert语句

assert语句的一般形式如下。

assert ,            #其中异常附加数据是可选的

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

举例:

def testAssert():
     for i in range (3):
        try:
           assert i<p>运行结果:</p><pre class="brush:php;toolbar:false">0
1
Raise a AssertionError!
2
end...

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

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

7.3.3 自定义异常类

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

class MyError (Exception):          #继承Exception类
     pass

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

Exception name Description

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!

Statement
This article is reproduced at:segmentfault. If there is any infringement, please contact admin@php.cn delete
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.