Exception handling in Python: boredom

Source: Internet
Author: User

What is an exception?

------Exception: Unhealthy condition

    • An exception is an event that occurs during program execution and affects the normal execution of the program. In general, an exception occurs when Python does not handle the program properly.
    • The exception is a Python object that represents an error.
    • When a Python script exception occurs, we need to capture and process it, or the program terminates execution.

Why the exception occurred:

Abnormal situation, in the program, there are two kinds of embodiment:

    • Code error or syntax error, program is not running!
    • In the course of running the program, the inappropriate data causes the program to crash due to some specific conditions.

For example: require the user to enter a number, but the user mistakenly entered a string, the type conversion will occur when the error causes the program to crash!

Why deal with exceptions?

when the program is running, due to the user's misoperation or inappropriate data caused by the program error, let the code to handle and ensure the normal execution of the program. Without causing the program to crash because of errors!

This improves the robustness of your code!

How to handle exceptions?

L Capture Handling Exceptions

L Assert Handling Exception "test exception information"

Capture Handling Exception Syntax:

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

The try/except statement is used to detect errors in a try statement block, allowing the except statement to catch exception information and handle it.

If you do not want to end your program when an exception occurs, simply capture it in a try.

Grammar:

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

1 Try:2 3< statements >#Run another code4 5 except< name >:6 7< statements >#if the ' name ' exception is thrown in the try section8 9 except< name >,< data >:Ten  One< statements >#if the ' name ' exception is thrown, get additional data A  - Else: -  the< statements >#If no exception occurs -  - finally: -  +< statements >#the statement to execute regardless of whether the try statement has an exception

Handling Exceptions:

1. Basic exception Handling

Try-except directly handles exceptions "can handle any exception-cannot locate what is specific"

try-except [Exception information] "can handle the specified exception"

2. Common exceptions

Super class for all exceptions: Baseexception

Super class for Standard exceptions: Exception (baseexception)

Exceptions that are often seen during program execution:

......

3. Handling multiple exceptions

Try-except (E1, E2, E3, ..., En) as e One except handles the specified multiple exceptions

Try-except e1-except e2-except E3 ... Each except handles the specified exception

In general, we want to see the exception information, we need to print the exception information-print the value of the e variable

Problem:

1) The system provides the exception information, obscure difficult to understand!

2) The system provides the exception information, after all limited!

4. Custom Exceptions

By creating a new Exception class, programs can name their own exceptions. Exceptions should be typical of inheriting from the exception class, either directly or indirectly.

The following is an example of a runtimeerror-related instance in which a class is created and the base class is RuntimeError, which is used to output more information when the exception is triggered.

In the TRY statement block, after the user-defined exception executes the EXCEPT block statement, the variable e is used to create an instance of the Networkerror class.

1 class Networkerror (runtimeerror): 2 3 def __init__ (Self, arg): 4 5 Self.args = arg

After you define the above class, you can trigger the exception as follows:

6 Try : 7  8 Raise networkerror ("badhostname")except networkerror,e:  One  A Print E.args
parameter of the exception

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

5. Proactively throwing exceptions

We can use the raise statement to trigger the exception ourselves

The raise syntax format is as follows:

Raise [Exception [, Args [, Traceback]]

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

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

Example

an exception can be a string, a class, or an object. The Python kernel provides exceptions, most of which are instantiated classes, which are parameters of an instance of a class.

It is very simple to define an exception as follows:

1 def functionname (level): 2 3     if level < 1:4         raise"Invalid level! " , level 5         # The code below to this would not being executed 6         # If we raise the exception  

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

For example, we capture the above exception, and the "except" statement looks like this:

7     Try : Business         Logic -here ... 9     except"Invalid level! " :
Ten Exception Handling here ... One else:12

During the development process, an active error is thrown to the program telling the program that an error has occurred.

6. Exception Handling Comprehension

Custom exceptions, just to throw an error, throw an error, are a serious warning of what's going on here.

First-the exception "system-standard exception" information is not very clear during code execution

Capturing system exceptions, creating a custom exception

Throws a custom exception "custom Exception" "Message Clear Error"

Purpose of Custom Exception: Transform exception information to convert ambiguous exception information to more accurate exception information

Conversion Exception Information: Exception Delivery ~ Pass a more explicit exception, to the following code to deal with!

Exception handling in Python: boredom

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.