Home Backend Development Python Tutorial Twelve exceptions for beginners to Python

Twelve exceptions for beginners to Python

Jan 16, 2017 pm 02:33 PM

在之前的编程练习中,也多次说过异常,这篇博客简单的说说异常。 
异常的语法: 
**try: 
检测范围 
except Exception[ as reason]: 
出现异常后解决的代码** 
(一定要注意缩进的对齐问题) 
下面简单的举个例子: 
之前说过,使用默认的打开一个不存在的文件时会出现文件不存在的异常,那咱们就以此为例,我以默认方式打开一个E盘中不存在的文件。

f=open("E:\\我为什么是一个文件.txt")     print(f.read())
     f.close()
Copy after login

结果系统会出现异常:

Twelve exceptions for beginners to Python

下面按照异常的解决办法来修改代码:

try:
     f=open("我为什么是一个文件.txt")     print(f.read())
     f.close()
except OSError:     print("文件出错啦!")
Copy after login

Twelve exceptions for beginners to Python

try:
     f=open("我为什么是一个文件.txt")
     print(f.read())
     f.close()#except OSError:#     print("文件出错啦!")except OSError as reason:
     print("文件出错啦\n错误的原因是:"+str(reason))finally:
     print("无论如何都会被执行的代码,例如文件的关闭")
Copy after login

异常也可以这么来处理,最后有一个finally语句,这条语句不管异常发生不发生都要执行。

Twelve exceptions for beginners to Python


最后简单说一下try-except-finally语句的执行过程: 
我们将可能产生异常的语句写在try语句里,程序运行时先执行try语句里面包含的内容,如果不发生异常,执行完try语句后,将跳过except语句,如果有finally语句,则执行finally语句,程序执行完毕。若try语句执行中出现异常,则跳出try语句,执行except中的语句,执行完except语句后,如果有finally语句,则执行finally语句,否则程序执行结束。

以上就是 Python零基础入门十二之异常的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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
3 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)

What are the common causes of OutOfMemoryError exceptions in Java? What are the common causes of OutOfMemoryError exceptions in Java? Jun 25, 2023 pm 08:43 PM

Java is one of the most widely used programming languages, but when developing applications using Java, it is easy to encounter "OutOfMemoryError" exception errors, which often bring some challenges to developers. What exactly causes the OutOfMemoryError exception in Java? Next, let’s take a closer look. Memory Leak (MemoryLeak) Memory leak refers to when an object cannot be recycled by the garbage collector, it will cause a memory leak.

Methods to solve Java reflection exception (ReflectiveOperationException) Methods to solve Java reflection exception (ReflectiveOperationException) Aug 26, 2023 am 09:55 AM

Methods to solve Java reflection exceptions (ReflectiveOperationException) In Java development, reflection (Reflection) is a powerful mechanism that allows programs to dynamically obtain and operate classes, objects, methods, properties, etc. at runtime. Through reflection, we can implement some flexible functions, such as dynamically creating objects, calling private methods, obtaining class annotations, etc. However, using reflection also brings some potential risks and problems, one of which is reflection anomalies (

MIT's latest masterpiece: using GPT-3.5 to solve the problem of time series anomaly detection MIT's latest masterpiece: using GPT-3.5 to solve the problem of time series anomaly detection Jun 08, 2024 pm 06:09 PM

Today I would like to introduce to you an article published by MIT last week, using GPT-3.5-turbo to solve the problem of time series anomaly detection, and initially verifying the effectiveness of LLM in time series anomaly detection. There is no finetune in the whole process, and GPT-3.5-turbo is used directly for anomaly detection. The core of this article is how to convert time series into input that can be recognized by GPT-3.5-turbo, and how to design prompts or pipelines to let LLM solve the anomaly detection task. Let me introduce this work to you in detail. Image paper title: Largelanguagemodelscanbezero-shotanomalydete

How to solve Java thread interrupt timeout exception (ThreadInterruptedTimeoutExceotion) How to solve Java thread interrupt timeout exception (ThreadInterruptedTimeoutExceotion) Aug 18, 2023 pm 01:57 PM

How to solve the Java thread interrupt timeout exception (ThreadInterruptedTimeoutException). In Java multi-thread programming, we often encounter situations where the thread execution time is too long. In order to prevent threads from occupying too many system resources, we usually set a timeout. When the thread execution time exceeds the timeout, we hope to be able to interrupt the execution of the thread. Java provides a thread interruption mechanism. By calling the thread's interrupt() method, you can

A guide to the unusual missions in the Rise of Ronin Pool A guide to the unusual missions in the Rise of Ronin Pool Mar 26, 2024 pm 08:06 PM

The abnormality in the pool is a side task in the game. Many players want to know how to complete the abnormality in the pool task. It is actually very simple. First, we must master the technique of shooting in the water before we can accept the task and investigate the source of the stench. Later, we discovered It turns out that there are a lot of corpses under the pool. Let’s take a look at this graphic guide for the unusual tasks in the pool in Rise of Ronin. Guide to unusual missions in the Ronin Rise Pool: 1. Talk to Iizuka and learn the technique of shooting in the water. 2. Go to the location in the picture below to receive the abnormal task in the pool. 3. Go to the mission location and talk to the NPC, and learn that there is a foul smell in the nearby pool. 4. Go to the pool to investigate. 5. Swim to the location in the picture below, dive underwater, and you will find a lot of corpses. 6. Use a camera to take pictures of the corpse. 7

How to solve Java network connection reset exception (ConnectionResetException) How to solve Java network connection reset exception (ConnectionResetException) Aug 26, 2023 pm 07:57 PM

How to solve the Java network connection reset exception (ConnectionResetException) When doing Java network programming, you often encounter the network connection reset exception (ConnectionResetException). This exception means that after the connection is established, the other host accidentally closed the connection. This may be caused by a crash of the other party's host, network interruption, or firewall configuration. When writing network applications, we need to handle this exception to ensure that the program can run normally

How to solve sound card driver abnormality How to solve sound card driver abnormality Feb 22, 2024 am 09:10 AM

Some users suddenly find that their sound card driver is abnormal when using the computer. If this happens, you can update the driver from the device manager or roll back the driver to see if the problem is solved successfully. How to solve sound card driver abnormality 1. Right-click "This PC" and select "Manage" 2. Click "Device Manager", click "Sound" 3. Right-click the driver and select "Properties" 4. Click "Driver" at the top, and then click below You can choose "Update or rollback"

C++ function exceptions and single testing: ensuring code soundness C++ function exceptions and single testing: ensuring code soundness May 03, 2024 am 09:18 AM

Exception handling and unit testing are important practices to ensure the soundness of C++ code. Exceptions are handled through try-catch blocks, and when the code throws an exception, it jumps to the catch block. Unit testing isolates code testing to verify that exception handling works as expected under different circumstances. Practical case: The sumArray function calculates the sum of array elements and throws an exception to handle an empty input array. Unit testing verifies the expected behavior of a function under abnormal circumstances, such as throwing an std::invalid_argument exception when an array is empty. Conclusion: By leveraging exception handling and unit testing, we can handle exceptions, prevent code from crashing, and ensure that the code behaves as expected under abnormal conditions.

See all articles