Python异常处理:try-except让你的代码更健壮

一文掌握python异常处理(try...except...) python异常处理(try...except...)详解 阅读详情

 

在编程中,异常(Exception)是程序运行时出现的错误或意外情况,例如文件找不到、网络连接失败、用户输入非法数据等。如果不对异常进行处理,程序可能会中断运行,导致用户体验不佳甚至数据丢失。Python 提供了强大的异常处理机制,通过 try-except 语句,可以捕获并处理异常,使代码更加健壮和可靠。本文将详细介绍 Python 中的异常处理机制,以及如何使用 try-except 让你的代码更加健壮。


1. 什么是异常?

异常是程序运行时出现的错误或意外情况,它会中断程序的正常执行。Python 中的异常是通过内置的异常类(如 ValueError、TypeError、FileNotFoundError 等)来表示的。当程序运行时触发异常时,Python 会抛出一个异常对象,如果没有捕获并处理这个异常,程序将终止运行。

示例 1:未处理的异常

Python复制

# 除以零的错误
result = 10 / 0

运行结果:

复制

Traceback (most recent call last):
  File "example.py", line 2, in <module>
    result = 10 / 0
ZeroDivisionError: division by zero

在上面的例子中,程序因为除以零而抛出了 ZeroDivisionError 异常,由于没有捕获和处理这个异常,程序直接中断运行。


2. 使用 try-except 捕获异常

为了避免程序因异常而中断,我们可以使用 try-except 语句来捕获并处理异常。try 块中的代码是可能会抛出异常的部分,而 exc

Python异常处理:新手村毕业必备技能,让你的代码更稳健! 还在为Python程序中恼人的Bug抓狂吗?💥 本文带你从零开始,掌握Python异常处理!🚀 学会像专业人士一样调试代码,让你的程序稳如磐石!💪 阅读详情

相关推荐

掌握Python异常处理:优雅地终止程序

本文深入探讨了在Python编程中进行异常处理的重要性以及如何实施。通过一个实际的项目启动报告意外中断的例子,说明了为什么需要异常处理。文章详细介绍了Python中的异常层次结构,并强调了自定义异常处理的必要性,包括使用try-except块来优雅地终止程序,并给出了相应的代码示例。此外,本文还讨论了在try-except控制流中代码执行的流程,异常信息的打印,以及使用多个except块来处理不同类型的异常。

weixin_36328210的博客 389

PLC中干湿球湿度计算:从原理到工程落地

温度参数的采集与控制是现代工业自动化系统的基础环节,而湿度作为环境控制中的关键指标,其测量方式在PLC工程实践中呈现出多样化的技术路径。干湿球测湿法是一种经典且经济的湿度测量方案,其核心原理基于干球温度与湿球温度之间的差值,结合饱和水汽压模型实现相对湿度的求解。该方案在暖通空调、农业大棚、洁净车间等场景中具有广泛的应用价值,尤其适合对长期稳定性和可维护性有较高要求的控制系统。在PLC平台上实现干湿球湿度计算,既可通过Magnus经验公式完成浮点运算,也可采用标准的二维湿度查算表配合数据块查表实现,工程中还需

weixin_29170327的博客 240

计算机网络(国家电网)

1.局域网中NOS(网络操作系统)提供的通信服务有工作站与工作站之间的对等通信,工作站与服务器之间的通信2.ISP:Internet服务商应用层 APDU(应用层协议数据单元)表示层 PPDU(表示层协议数据单元)会话层 SPDU(会话层协议数据单元)传输层 segment(报文段)网络层 packet (数据包)数据链路层 frame(数据帧)物理层 bit (比特)4.

qq_31715647的博客 3201

R3LIVE 1.0 适配 Velodyne 16线雷达:3步配置解决150米漂移问题

本文详细解析了R3LIVE 1.0适配Velodyne 16线雷达时出现的150米漂移问题,并提供三步配置方案。通过调整雷达类型设置、运动补偿与时间对齐、视觉-激光联合优化等关键参数,有效解决了系统漂移问题,提升定位精度。适用于机器人定位与建图领域的开发者。

weixin_29054195的博客 275

TI Sitara PRU可编程实时单元:工业自动化中的硬实时协处理器解析

在嵌入式系统与工业自动化领域,实时性和确定性是核心需求。实时性指系统对外部事件做出响应的可预测时间,确定性则要求响应时间严格一致,不受其他任务干扰。其技术原理通常通过专用硬件或实时操作系统实现,例如采用独立于主CPU的协处理器来处理高精度时序任务。这种设计的技术价值在于,它能将主CPU从高实时性要求的任务中解放出来,专注于复杂业务逻辑,同时确保关键IO操作达到纳秒级延迟和极低抖动。应用场景广泛覆盖伺服电机控制、工业通信协议加速和多接口扩展等。本文聚焦的TI Sitara系列PRU(可编程实时单元),正是此类

weixin_42526068的博客 292

【搭建实战】全国天气预报看板搭建

不仅如此,码匠还一站式提供了企业内部系统常用的租户管理、细粒度的权限控制、审计日志等功能,让您快速搭建后台应用的同时,也为您的企业信息安全保驾护航。是一款国内研发的开发者友好的低代码平台,您无需了解React/Vue等框架的开发、部署等各种细节,就可以快速打通前后端,连接RESTAPI、MySQL、MongoDB等多种数据源,然后通过一套开箱即用的组件,轻松搭建功能完善的数据看板、数据洞察、Admin管理后台等多种应用。天气预报对我们的各项活动有很大的帮助,可以让我们合理安排自己的出行等活动。...

weixin_39545889的博客 433

Android 10.0 SystemUI下拉状态栏点击设置跳转设置时白屏修改

在10.0的系统rom定制化开发中,在SystemUI下拉状态栏下方点击设置图标跳转设置的过程中,发现 有白屏显示挡住设置界面,显示白屏,接下来分析下相关原因来解决这个问题

安卓兼职framework和app工程师的博客 93

一文弄懂Word2Vec之skip-gram(含详细代码)

目录 前言 一、什么是Skip-gram算法 二、目标是什么 三、定义表示法 3.1 one-hot向量 3.2 词向量(word vector) 3.3 单词矩阵 3.4 单词相似度 3.5 softmax函数 3.6算法过程 3.7 求softmax 四、skipgram代码实现 4.1 如何把词转换为向量 4.2 CBOW和Skip-gram的算法实现 Skip-gram的理想实现 Skip-gram的实际实现 4.3 使用Pytorch实现Skip-gram .

Python,数据分析,机器学习,深度学习 1万+

Java 实现 MP3 音频合并工具类:摆脱 FFmpeg,高效低 CPU 的纯本地方案【需求已解决】

本方案充分发挥了 Java 音频 SPI 的潜力,实现了轻量、跨平台、低 CPU 消耗的 MP3 音频合并工具类。 对于希望在服务器或桌面应用中集成音频处理功能的开发者而言,这无疑是一个可行且优雅的解决方案。

一键难忘的博客 555

迈瑞BS系列全自动生化分析仪LIS协议接口手册(内含HL7和ASTM)

迈瑞BS系列全自动生化分析仪LIS协议接口手册,内含HL7和ASTM)

TMS_WebGMaps_1.9.8.0_Full_Source

TMS_WebGMaps_1.9.8.0_Full_Source 全源码 delphi cbuilder

贝叶斯统计 [韦来生编]

贝叶斯(Bayes)统计是近几十年来迅速发展起来的数理统计的一个重要分支。贝叶斯方法与经典统计方法的主要不同之处是进行统计推断时除了利用样本信息外,还要利用参数的先验信息,因此可以提高统计推断或统计决策的效果。它在经济、金融、生物、医学、自然科学和社会科学等许多领域具有广泛的应用。贝叶斯方法的研究已渗透到了统计学的几乎所有领域。作者在给中国科学技术大学概率论与数理统计专业本科生开设的“数理统计”课程中有一章专门讲授“贝叶斯方法和统计决策理论”,近十年来也给中国科学技术大学概率统计专业研究生开设过几次“贝叶斯分析”课。本书是在对过去讲稿的内容作了适当的增减和调整的基础上完成的。  本书共分六章。第1章是绪论,介绍了贝叶斯统计的若干基本概念,同时对必要的数理统计的基础知识有重点地作了回顾。第二章介绍了确定先验分布的若干可供选择的方法。第三章介绍了几类常见统计模型参数的后验分布的主要结果和计算方法。第四章和第五章分别介绍了“贝叶斯统计推断”和“贝叶斯统计决策”的内容。第六章介绍了贝叶斯统计计算的若干方法,包括蒙特卡洛方法和马尔可夫链蒙特卡洛(MCMC)方法以及相关统计软件的简介。本书的每一章附右大量的例题和习题,书末附有常用的几个表格和部分习题解答供读者查用。  大约可在54学时内讲授本书的第1章至第六章的主要内容,教师可根据学时需要选讲本书第1章至第六章的部分内容。书中标“*”号的章节可略去不讲,留给读者作为阅读材料。第六章例题中的R代码和部分例题的数据文件等可从作者个人主页下载。  作者在编写本书的过程中参考了J.O.Berger教授的《统计决策论及贝叶斯分析》和茆诗松教授编写的《贝叶斯统计》等书中的一些内容,以及《贝叶斯分析》一书中由张伟平博士编写的有关贝叶斯统计计算的一些内容。在此表示衷心感谢。  本书编写准备过程中,中国科学技术大学统计与金融系的几个研究生帮助完成了本书部分中文的录入和排版,作者对他们的辛勤工作表示真诚的感谢。高等教育出版社为本书的出版给予了大力支持。在此一并致谢。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

上一篇: Python文件操作:读写文件的简单方法
下一篇: Python模块与包:如何组织你的代码
普通网友
博客等级 码龄4年 280粉丝 53原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

AI软件改变生活

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值
⌂ 换网址