Home Backend Development Python Tutorial Python exception handling

Python exception handling

Nov 23, 2016 am 09:15 AM
python

Python provides two very important functions to handle exceptions and errors that occur when python programs are running. You can use this feature to debug python programs.

Exception handling: This site’s Python tutorial will introduce it in detail.

Assertions: This site’s Python tutorial will introduce them in detail.

Python standard exception

Exception name

Description

BaseException Base class for all exceptions

SystemExit Interpreter request to exit

KeyboardInterrupt User interrupts execution (usually Enter^C)

Exception General Error base class

StopIteration The iterator has no more values ​​

GeneratorExit An exception occurs in the generator to notify the exit

SystemExit The Python interpreter requests to exit

StandardError Base class for all built-in standard exceptions

ArithmeticError Base class for all numerical calculation errors

FloatingPointError Floating point calculation error

OverflowError Numerical operation exceeds the maximum limit

ZeroDivisionError Division (or modulo) zero (all data types)

AssertionError Assertion statement failed

AttributeError The object does not have this attribute

EOFError No built-in input, EOF flag reached

EnvironmentError Base class for operating system errors

IOError Input/output operation failed

OSError Operating system error

WindowsError System call failed

ImportError Failed to import module/object

KeyboardInterrupt User interrupts execution (usually input ^C)

LookupError Base class for invalid data query

IndexError There is no such index in the sequence

KeyError There is no such key in the map

MemoryError Memory overflow error (for Python explanation) The device is not fatal)

NameError Undeclared/initialized object (no properties)

UnboundLocalError Accessing uninitialized local variable

ReferenceError Weak reference trying to access an object that has been garbage collected

RuntimeError General runtime Error

NotImplementedError Method not yet implemented

SyntaxError Python syntax error

IndentationError Indentation error

TabError Mixing tabs and spaces

SystemError General interpreter system error

TypeError Invalid operation on type

ValueError Invalid input Parameters

UnicodeError Unicode related errors

UnicodeDecodeError Unicode decoding error

UnicodeEncodeError Unicode encoding error

UnicodeTranslateError Unicode conversion error

Warning Warning base class

DeprecationWarning Warning about deprecated features

FutureWarning       Warning that the semantics of the construct will change in the future                                                                                                           out out out out out out out of                     out out. out out out off out out out out belonging out out belonging outft out Through out through out through out through out  through    ‐    to  ‐                                                     . ) Warning

SyntaxWarning Suspicious syntax warning

UserWarning Warning generated by user code

What is an exception?

An exception is an event that occurs during program execution and affects the normal execution of the program.

Generally, an exception occurs when Python cannot handle the program normally.

Exceptions are Python objects that represent an error.

When an exception occurs in a Python script, we need to catch and handle it, otherwise the program will terminate execution.

Exception handling

To catch exceptions, try/except statements can be used.

The try/except statement is used to detect errors in the try statement block, so that the except statement can capture exception information and handle it.

If you don’t want to end your program when an exception occurs, just catch it in try.

Grammar:

The following is the syntax of a simple try....except...else:

try:

;:

Additional data

else:

          #If no exception occurs

The working principle of try is that when a try statement is started, python marks it in the context of the current program , so that you can return here when an exception occurs. The try clause is executed first, and what happens next depends on whether an exception occurs during execution.

If an exception occurs when the statement after try is executed, python will jump back to try and execute the first except clause matching the exception. After the exception is handled, the control flow will pass through the entire try statement (unless it is processed again when handling the exception) throws a new exception).

If an exception occurs in the statement after try, but there is no matching except clause, the exception will be submitted to the upper try, or to the top level of the program (this will end the program and print the default error message) .

If no exception occurs when the try clause is executed, python will execute the statement after the else statement (if there is an else), and then the control flow passes through the entire try statement.

Example

The following is a simple example, it opens a file, writes the content in the file, and no exception occurs:

#!/usr/bin/python

try:

fh = open("testfile", "w")

fh.write("This is my test file for exception handling!!")

except IOError:

print "Error: can't find file or read data"

else:

print "Written content in the file successfully"

fh.close()

The output of the above program:

Written content in the file successfully

Instance

The following is a simple example, it opens a file and writes the content in the file, but the file does not have write permission, an exception occurred:

#!/usr/bin/python

try:

fh = open("testfile", "w")

fh.write("This is my test file for exception handling!!")

except IOError:

print "Error: can't find file or read data"

else:

print "Written content in the file successfully"

The output of the above program:

Error: can't find file or read data

Use except without any exception type

You can use except without any exception type, as shown below:

try:

You do your operations here;

........................

except:

If there is any exception, then execute this block.

 ........................

else:

If there is no exception then execute this block.

The above method The try-except statement catches all exceptions that occur. But this is not a good way, we cannot identify specific abnormal information through this program. Because it catches all exceptions.

Use except to bring multiple exception types

You can also use the same except statement to handle multiple exception messages, as shown below:

try:

You do your operations here;

. ..................

except(Exception1[, Exception2[,...ExceptionN]]]):

If there is any exception from the given exception list,

then execute this block.

........................

else:

If there is no exception then execute this block.

try-finally statement

try-finally statement will execute the last code regardless of whether an exception occurs.

try:

finally:

#Always executed when exiting try

raise

Note: You can use the except statement or the finally statement, but you cannot use both at the same time. The else statement cannot be used at the same time as the finally statement. write("This is my test file for exception handling!!")

finally:

print "Error: can't find file or read data"

If the open file does not have writable permissions , the output is as follows:

Error: can't find file or read data

The same example can also be written as follows:

#!/usr/ bin/python

try:

fh = open("testfile", "w")

try:

fh.write("This is my test file for exception handling!!")

finally:

 print "Going to close the file"

 fh.close()

except IOError:

print "Error: can't find file or read data"

When in try block Throw an exception and execute the finally block code immediately.

After all statements in the finally block are executed, the exception is raised again and the except block code is executed.

The content of parameters is different from exceptions.

Exception parameters

An exception can have parameters, which can be used as output exception information parameters.

You can capture exception parameters through the except statement, as shown below:

try:

You do your operations here;

............. .......

except ExceptionType, Argument:

You can print value of Argument here...

The exception value received by the variable is usually included in the exception statement. Variables in the form of tuples can receive one or more values.

Tuples usually contain error strings, error numbers, and error locations.

Instance

The following is an example of a single exception:

#!/usr/bin/python

# Define a function here.

def temp_convert(var):

try:

return int(var)

except ValueError, Argument:

print "The argument does not contain numbersn", Argument

# Call above function here.

temp_convert("xyz");

The execution result of the above program is as follows:

The argument does not contain numbers

invalid literal for int() with base 10: 'xyz'

To trigger an exception

we can use The raise statement triggers an exception by itself

The raise syntax format is as follows:

raise [Exception [, args [, traceback]]]

Exception in the statement is the type of exception (for example, NameError) parameter is an exception parameter value. This parameter is optional, if not provided, the exception parameter is "None".

The last parameter is optional (rarely used in practice) and, if present, is the trace exception object.

Instance

An exception can be a string, class or object. Most of the exceptions provided by the Python kernel are instantiated classes, which are parameters of an instance of a class.

Defining an exception is very simple, as follows:

def functionName(level):

if level < 1:

raise "Invalid level!", level

# The code below to this would not be executed

        # if we raise the exception

 

 

Note: In order to be able to catch the exception, the "except" statement must use the same exception to throw the class object or string.

For example, if we catch the above exception, the "except" statement is as follows:

try:

Business Logic here...

except "Invalid level!":

Exception handling here...

else:

Rest of the code here...

User-defined exceptions

By creating a new exception class, programs can name their own exceptions . Exceptions should typically inherit from the Exception class, either directly or indirectly.

The following is an example related to RuntimeError. A class is created in the example. The base class is RuntimeError, which is used to output more information when an exception is triggered.

In the try statement block, the except block statement is executed after the user-defined exception. The variable e is used to create an instance of the Networkerror class.

class Networkerror(RuntimeError):

def __init__(self, arg):

self.args = arg

After defining the above class, you can trigger the exception, As shown below:

try:

raise Networkerror("Bad hostname")

except Networkerror,e:

print e.args


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 admin@php.cn

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)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to solve the permissions problem encountered when viewing Python version in Linux terminal? How to solve the permissions problem encountered when viewing Python version in Linux terminal? Apr 01, 2025 pm 05:09 PM

Solution to permission issues when viewing Python version in Linux terminal When you try to view Python version in Linux terminal, enter python...

How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? How to efficiently copy the entire column of one DataFrame into another DataFrame with different structures in Python? Apr 01, 2025 pm 11:15 PM

When using Python's pandas library, how to copy whole columns between two DataFrames with different structures is a common problem. Suppose we have two Dats...

Python hourglass graph drawing: How to avoid variable undefined errors? Python hourglass graph drawing: How to avoid variable undefined errors? Apr 01, 2025 pm 06:27 PM

Getting started with Python: Hourglass Graphic Drawing and Input Verification This article will solve the variable definition problem encountered by a Python novice in the hourglass Graphic Drawing Program. Code...

Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Python Cross-platform Desktop Application Development: Which GUI Library is the best for you? Apr 01, 2025 pm 05:24 PM

Choice of Python Cross-platform desktop application development library Many Python developers want to develop desktop applications that can run on both Windows and Linux systems...

Do Google and AWS provide public PyPI image sources? Do Google and AWS provide public PyPI image sources? Apr 01, 2025 pm 05:15 PM

Many developers rely on PyPI (PythonPackageIndex)...

How to efficiently count and sort large product data sets in Python? How to efficiently count and sort large product data sets in Python? Apr 01, 2025 pm 08:03 PM

Data Conversion and Statistics: Efficient Processing of Large Data Sets This article will introduce in detail how to convert a data list containing product information to another containing...

How to optimize processing of high-resolution images in Python to find precise white circular areas? How to optimize processing of high-resolution images in Python to find precise white circular areas? Apr 01, 2025 pm 06:12 PM

How to handle high resolution images in Python to find white areas? Processing a high-resolution picture of 9000x7000 pixels, how to accurately find two of the picture...

How to solve the problem of file name encoding when connecting to FTP server in Python? How to solve the problem of file name encoding when connecting to FTP server in Python? Apr 01, 2025 pm 06:21 PM

When using Python to connect to an FTP server, you may encounter encoding problems when obtaining files in the specified directory and downloading them, especially text on the FTP server...

See all articles