Python learning - exceptions
的 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.
‐ 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'
Output:
Python code
Enter something --> + Done
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 '\nWhy did you do an EOF on me?' except ShortInputException, x: print 'ShortInputException: The input was of length %d, \ was expecting at least %d' % (x.length, x.atleast) else: print 'No exception was raised.'
Enter something --> 2222 No exception was raised. Enter something --> 1 ShortInputException: The input was of length 1, was expecting at least 3
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.
The example of using finally is as follows:
import time f = file('poem.txt') try: while True: line = f.readline() if len(line) == 0: break time.sleep(2) print line, finally: f.close() print 'Cleaning up...closed the file'
Programming is fun When the work is done if you wanna make your work also fun: use Python! Cleaning up...closed the file

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

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



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

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 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 when using FiddlerEverywhere for man-in-the-middle readings When you use FiddlerEverywhere...

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? Uvicorn is a lightweight web server based on ASGI. One of its core functions is to listen for HTTP requests and proceed...

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

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