Home Backend Development Python Tutorial Python learning - exceptions

Python learning - exceptions

Dec 09, 2016 pm 02:05 PM

的 Exception

When some abnormal conditions appear in your program, abnormalities occur. For example, when you want to read a certain file, and that file does not exist. Or you accidentally deleted it while the program was running. The above situations can be handled using exceptions.

           What will happen if there are some invalid statements in your program? Python will handle situations like this by raising and telling you there's an error.

try..except

      1. Handle exceptions

                                                                                                            ‐ out 1. Handle exceptions
                ‐ outs out of ’s 1. Handle exceptions to be handled with try..except statement-. We put our normal statements in try-blocks and our error handling statements in except-blocks.
An example of handling exceptions is as follows:

import sys
try:
    s = raw_input('Enter something --> ')
except EOFError:
    print '\nWhy did you do an EOF on me?'
    sys.exit()
except:
    print '\nSome error/exception occurred.' 
print 'Done'
Copy after login

Output:

Python code

Enter something --> +  
Done
Copy after login

We put all statements that may cause errors in try blocks, and then handle all errors and exceptions in except clauses/blocks.从 Except clauses can specifically handle single errors or abnormalities, or a set of errors/abnormalities included in parentheses. If no error or exception name is given, it will handle all errors and exceptions. For every try clause, there is at least one associated except clause.
        If an error or exception is not handled, the default Python handler will be called. It will terminate the program and print a message, which we have already seen done.
You can also associate the try..catch block with an else clause. When no exception occurs, the else clause will be executed.

2. Raise an exception
We can also get the exception object to get more information about this exception.
You can use the raise statement to raise an exception. You also have to specify the name of the error/exception and the exception object that was triggered with the exception. The errors or exceptions you can raise should be a direct or indirect derived class of the Error or Exception class respectively.
An example of how to raise an exception is as follows:

class ShortInputException(Exception):
    '''A user-defined exception class.'''
    def __init__(self, length, atleast):
        Exception.__init__(self)
        self.length = length
        self.atleast = atleast
try:
    s = raw_input('Enter something --> ')
    if len(s) < 3:
        raise ShortInputException(len(s), 3)
except EOFError:
    print &#39;\nWhy did you do an EOF on me?&#39;
except ShortInputException, x:
    print &#39;ShortInputException: The input was of length %d, \
          was expecting at least %d&#39; % (x.length, x.atleast)
else:
    print &#39;No exception was raised.&#39;
Copy after login

Output:

Python code

Enter something --> 2222  
No exception was raised.  
Enter something --> 1  
ShortInputException: The input was of length 1,           was expecting at least 3
Copy after login

Here, we have created our own exception type, in fact we can use any predefined exception/error. This new exception type is the ShortInputException class. It has two fields: length is the length of the given input, and atleast is the minimum length expected by the program.

            In the except clause, we provide the error class and variables used to represent the error/exception object. This is similar to the concept of formal parameters and actual parameters in function calls. In this particular except clause, we use the length and atleast fields of the exception object to print an appropriate message to the user.


try..finally

If you are reading a file and want to close the file regardless of whether an exception occurs, what should you do? This can be done using finally block. Note that you can use both an except clause and a finally block within a try block. If you want to use them at the same time, you need to embed one into the other.

The example of using finally is as follows:

import time
f = file(&#39;poem.txt&#39;)
try:  
    while True:
        line = f.readline()
        if len(line) == 0:
            break
        time.sleep(2)
        print line,
finally:
    f.close()
    print &#39;Cleaning up...closed the file&#39;
Copy after login

Output:

Python code

Programming is fun  
When the work is done  
if you wanna make your work also fun:  
        use Python!  
Cleaning up...closed the file
Copy after login
We carry out the usual file reading work, but I intentionally use the time.sleep method to pause for 2 seconds before printing a line. The reason for this is to make the program run slower (Python usually runs very fast due to its nature). While the program is running, press Ctrl-c to interrupt/cancel the program. We can observe that the KeyboardInterrupt exception is triggered and the program exits. But before the program exits, the finally clause is still executed and the file is closed.


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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

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...

How to teach computer novice programming basics in project and problem-driven methods within 10 hours? How to teach computer novice programming basics in project and problem-driven methods within 10 hours? Apr 02, 2025 am 07:18 AM

How to teach computer novice programming basics within 10 hours? If you only have 10 hours to teach computer novice some programming knowledge, what would you choose to teach...

How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? How to avoid being detected by the browser when using Fiddler Everywhere for man-in-the-middle reading? Apr 02, 2025 am 07:15 AM

How to avoid being detected when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

What are regular expressions? What are regular expressions? Mar 20, 2025 pm 06:25 PM

Regular expressions are powerful tools for pattern matching and text manipulation in programming, enhancing efficiency in text processing across various applications.

How does Uvicorn continuously listen for HTTP requests without serving_forever()? How does Uvicorn continuously listen for HTTP requests without serving_forever()? Apr 01, 2025 pm 10:51 PM

How does Uvicorn continuously listen for HTTP requests? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

What are some popular Python libraries and their uses? What are some popular Python libraries and their uses? Mar 21, 2025 pm 06:46 PM

The article discusses popular Python libraries like NumPy, Pandas, Matplotlib, Scikit-learn, TensorFlow, Django, Flask, and Requests, detailing their uses in scientific computing, data analysis, visualization, machine learning, web development, and H

How to dynamically create an object through a string and call its methods in Python? How to dynamically create an object through a string and call its methods in Python? Apr 01, 2025 pm 11:18 PM

In Python, how to dynamically create an object through a string and call its methods? This is a common programming requirement, especially if it needs to be configured or run...

See all articles