


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.
Exception name | Description |
---|---|
Call Exception raised by non-existent method | |
Exception raised by encountering the end of file | |
Exception caused by import module error | |
Exception caused by list out of bounds | |
Exceptions caused by I/O operations, such as errors in opening files, etc. | |
Exceptions caused by using keywords that do not exist in the dictionary | |
Exception caused by using a non-existent variable name | |
Exception caused by incorrect statement block indentation | |
Exception raised by a value that does not exist in the search list | |
The divisor is Exception raised by zero |
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!

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

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

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

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

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

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

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver CS6
Visual web development tools

WebStorm Mac version
Useful JavaScript development tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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.