Python异常处理

我们一般使用try-except语句来进行异常处理。

使用except Exception as err可以统一捕捉所有异常,而也可以分开处理单个异常。

# 分开捕捉单个异常

try:
num1 = int(input('Enter the first number:'))
num2 - int(input('Enter the sencond number:'))
print(num1 / num2)
except ValueError: #捕捉数字转化异常
print('Please input a digit!')
except ZeroDivisionError: #捕捉除0异常
print('The second number cannot be zero') # 两种异常一起捕捉 try:
num1 = int(input('Enter the first number:'))
num2 - int(input('Enter the sencond number:'))
print(num1 / num2)
except (ValueError,ZeroDivisionError):
print('Invalid input!') # 统一捕捉所有异常 try:
num1 = int(input('Enter the first number:'))
num2 - int(input('Enter the sencond number:'))
print(num1 / num2)
except Exception as err:
print('Something webt wrong!')
print(err)

else语句

try-except还可以和else一起使用,如果语句中没有异常引发,那么这个else语句就会执行。

try:
num1 = int(input('Enter the first number:'))
num2 - int(input('Enter the sencond number:'))
print(num1 / num2)
except (ValueError,ZeroDivisionError):
print('Invalid input!')
else:
print('Aha, everything is OK.')

循环

如果我们想要用户直到输入正确,那么就要使用循环,使用while True加上break语句

while True:
try:
num1 = int(input('Enter the first number:'))
num2 - int(input('Enter the sencond number:'))
print(num1 / num2)
except (ValueError,ZeroDivisionError):
print('Invalid input!')
print('Aha, everything is OK.')

Finally语句

finallyelse不一样,不管有没有异常引发,finally语句都要执行。

try:
num1 = int(input('Enter the first number:'))
num2 - int(input('Enter the sencond number:'))
print(num1 / num2)
except (ValueError,ZeroDivisionError):
print('Invalid input!')
finally:
print('It is a finally clause.')

上下文管理器(Context Manager)和With语句

如果我们打开文件使用下面的代码,在finally语句中,因为f可能没被成功定义,可能还是会报错。

try:
f = open('data.txt')
for line in f:
print(line, end ='')
except IOError:
print('Cannnot open the file!')
finally:
f.close()

而我们可以使用下面的代码打开文件,通过这个上下文管理器可以定义和控制代码块执行前的准备动作及执行后的收尾动作。

with open('data.txt') as f:
for line in f:
print(line, end='')

【Python学习笔记】异常处理try-except的更多相关文章

  1. Python学习笔记(异常处理)

    用户输入了一个不合规定的值,或者需要打开的文件不存在.这些情况被称作“异常”,一个好的程序需要能处理可能发生的异常,避免程序因此而中断. 例如我们去打开一个文件: f = file('non-exis ...

  2. python学习笔记(六)文件夹遍历,异常处理

    python学习笔记(六) 文件夹遍历 1.递归遍历 import os allfile = [] def dirList(path): filelist = os.listdir(path) for ...

  3. Python学习笔记之异常处理

    1.概念 Python 使用异常对象来表示异常状态,并在遇到错误时引发异常.异常对象未被捕获时,程序将终止并显示一条错误信息 >>> 1/0 # Traceback (most re ...

  4. Python学习笔记进阶篇——总览

    Python学习笔记——进阶篇[第八周]———进程.线程.协程篇(Socket编程进阶&多线程.多进程) Python学习笔记——进阶篇[第八周]———进程.线程.协程篇(异常处理) Pyth ...

  5. python学习笔记目录

    人生苦短,我学python学习笔记目录: week1 python入门week2 python基础week3 python进阶week4 python模块week5 python高阶week6 数据结 ...

  6. Python学习笔记之基础篇(-)python介绍与安装

    Python学习笔记之基础篇(-)初识python Python的理念:崇尚优美.清晰.简单,是一个优秀并广泛使用的语言. python的历史: 1989年,为了打发圣诞节假期,作者Guido开始写P ...

  7. Python 学习笔记(下)

    Python 学习笔记(下) 这份笔记是我在系统地学习python时记录的,它不能算是一份完整的参考,但里面大都是我觉得比较重要的地方. 目录 Python 学习笔记(下) 函数设计与使用 形参与实参 ...

  8. 大学四年的Python学习笔记分享之一,内容整理的比较多与仔细

    翻到以前在大学坚持记录的Python学习笔记,花了一天的时间整理出来,整理时不经回忆起大学的时光,一眨眼几年就过去了,现在还在上学的你们,一定要珍惜现在,有个充实的校园生活.希望这次的分享对于你们有学 ...

  9. python学习笔记整理——字典

    python学习笔记整理 数据结构--字典 无序的 {键:值} 对集合 用于查询的方法 len(d) Return the number of items in the dictionary d. 返 ...

  10. VS2013中Python学习笔记[Django Web的第一个网页]

    前言 前面我简单介绍了Python的Hello World.看到有人问我搞搞Python的Web,一时兴起,就来试试看. 第一篇 VS2013中Python学习笔记[环境搭建] 简单介绍Python环 ...

随机推荐

  1. 父类属性值的copy

    最近开发中遇到这样一个问题将父类的属性值copy到子类中,从而对子类添加一些其他属性. 父类: package com.jalja.org.jms.test01; import java.util.D ...

  2. BZOJ 1202 狡猾的商人(带权并查集)

    给出了l,r,w.我们就得知了s[r]-s[l-1]=w.也就是说,点l-1和点r的距离为w. 于是可以使用带权并查集,定义dis[i]表示点i到根节点的距离.查询和合并的时候维护一下就OK了. 如果 ...

  3. 进程间通讯-2(pipe)

    通过pipe 管道的方式也可以实现进程间通信. 父进程和子进程之间可以实现相互通信. from multiprocessing import Process, Pipe def f(conn): co ...

  4. BZOJ5217:[Lydsy2017省队十连测]航海舰队——题解

    https://www.lydsy.com/JudgeOnline/problem.php?id=5217 Byteasar 组建了一支舰队!他们现在正在海洋上航行着.海洋可以抽象成一张n×m 的网格 ...

  5. 使用openssl进行文件加密

    #include <iostream> #include <string> #include <stdlib.h> using namespace std; int ...

  6. scanf函数用法小记

    By francis_hao    Aug 26,2017   scanf – 输入格式转换   概述 #include <stdio.h>int scanf(const char *fo ...

  7. Linux下 ps -ef 和 ps aux 的区别及格式详解

    原文:https://www.cnblogs.com/5201351/p/4206461.html Linux下ps -ef和ps aux的区别及格式详解 Linux下显示系统进程的命令ps,最常用的 ...

  8. CentOS 6.5 下安装配置 mysql

    如果要在Linux上做j2ee开发,首先得搭建好j2ee的开发环境,包括了jdk.tomcat.eclipse的安装(这个在之前的一篇随笔中已经有详细讲解了Linux学习之CentOS(七)--Cen ...

  9. Codeforces Round #342 (Div. 2) B

    B. War of the Corporations time limit per test 1 second memory limit per test 256 megabytes input st ...

  10. Java Zip压缩

    1.压缩文件或整个目录 // ZipCompression.java import java.io.File;import java.io.FileInputStream;import java.io ...