Python Exception handling

Source: Internet
Author: User
Tags finally block

First, Python what is an exception

An exception is a time when the event occurs during the execution of the program, affecting the normal execution of the program. In general, an exception occurs when Python does not handle the program properly.

To prevent users from seeing unfriendly places, avoid the abnormal exit of the program.

Second, Python exception handling

You can use the Try/except statement to catch an exception.

The following is a simple syntax for try...except...else:

Try

< statements > # Run another code

Except < name:

< Statement > # if the ' name ' exception is thrown in the try Section

Except < name >,< data;:

< Statement > # if the ' name ' exception is thrown, get additional data

Else

< statement > # If no exception occurred

Iii. How Python try Works

Try works by starting a try statement, and Python is tagged in the context of the current program so that when an exception occurs, it can go back here, the TRY clause executes first, and what happens next depends on whether an exception occurs at execution time.

If an exception occurs after a try statement executes, Python jumps back to the try and executes the first except clause that matches the exception, the exception is processed, the control flow passes through the entire try statement, and if an exception occurs in the statement after the try and there is no matching except clause, Exceptions will be submitted to the upper try, or to the top of the program. This will end the program and print a default error message. The TRY clause does not have an exception during execution, and Python executes the statement after the ELSE clause, ending with the entire control flow.

Iv. Examples of Python exceptions

1. Open a file, write the content in the file, and no exception occurred;

2. It opens a file that writes content to the file, but the file does not have write permission and an exception occurs.

Try
f = open ("Test.txt", ' W ')
F.write ("This was my test file for exception handing.")
Except IOError:
Print ("Error:can ' t find file or read data.")
Else
Print ("Written content in the file successfully.")
F.close ()
Print ("done!")

V. Python uses except without any exception type

Try

your operations here;

Except

If There is any Exception,then the execute this block.

Else

If there is no exception then execute this block.

This way you can catch all the exceptions, but this does not well identify the exception information.

Vi. Python uses excepte with multiple exception types

Try

your operations here;

Except (exception1[,exception2[,... Exceptionn]]):

If there is a exception from the given exception List,then execute this block.

Else

If there is no exception then execute this block.

Vii. Python try-finally Statements

The try-finally statement executes the final code regardless of whether an exception occurs.

Try

< statements >

Finally

< Statement > # always executes when a try is launched

Raise

Note: You can use the except statement or the finally statement alone, but both cannot be used at the same time. Else statements cannot be used in conjunction with the finally statement.

Viii. Python try-finally Statements

Examples: try-finally and try-except are nested and used to ensure that files are closed in a timely manner regardless of whether an exception has been written.

Try:Fh=Open( "testfile" ,  try: Fh. ( "This is a test file for testing exceptions!!"   finally:   "close file"  Fh. () except ioerror : print  "Error: Failed to find file or read file "               

Executes the finally block code immediately when an exception is thrown in the try block.

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

The contents of the parameter differ from the exception.

parameter of the exception

An exception can take a parameter that can be used as the output exception information parameter.

You can use the except statement to catch the parameters of the exception, as follows:

Try:     normal operation    ......... ........ exceptexceptiontype,Argument: You can output Argument value  in this   ... 

The exception value that the variable receives is usually contained in the exception's statement. In a tuple's form, a variable can receive one or more values.

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

Instance

The following is an instance of a single exception:

#!/usr/bin/python#-*-Coding:utf-8-*-# Defining functionsDef Temp_convert (var Span class= "KWD" >try: returnint (varexcept valueerror, Span class= "Typ" >argument: print  "parameter does not contain a number \ n" , argument# call function temp_convert ( "XYZ"    

The results of the above program execution are as follows:

$ python test.  parameter does not contain a number for  int() withbase:' xyz '

Try
1/0
Except Exception as E:
"' Exception of the parent class that can catch all exceptions '
Print ("0 cannot be removed")
Else
"Protect code that does not throw exceptions"
Print ("no exception")
Finally
Print ("Finally always executes Me")

Python Exception handling

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.