`
wx1568037608
  • 浏览: 33447 次
最近访客 更多访客>>
文章分类
社区版块
存档分类
最新评论

What is the difference between try/except and assert?

 
阅读更多

assert only check if a condition is true or not and throw an exception. A try/except block can run a few statements and check if any of them throw an exception so you can process it in the exceptpart. Examples:

assert(1 == 2)

will give you an AsertionError.

try:
    # some statements
    # ...
except OSError as err:
    #If an OSerror exception is thrown, you can process it here. For example:
    print("OS error: {0}".format(err))

Your code will look like this:

def function_addition(x,y):
    try:
        assert (y!=0)
    except:
        raise ValueError('y is 0.')
    total= x/y
    return total


num1=float(input("Write a number :"))
num2=float (input("Write a second number:"))
try:
    result=function_addition(num1,num2)
except ValueError as ve:
    print(ve)
else:
    print(result)

If you save it in a fun.py file and run it, you will have this output:

Write a number :1
Write a second number:2
0.5
# Run it again.
Write a number :0
Write a second number:0
y is 0.
分享到:
评论

相关推荐

    Python中的异常处理try/except/finally/raise用法分析

    本文实例分析了Python中的异常处理try/except/finally/raise用法。分享给大家供大家参考,具体如下: 异常发生在程序执行的过程中,如果python无法正常处理程序就会发生异常,导致整个程序终止执行,python中使用try...

    【Java设计模式-源码】Arrange/Act/Assert模式:增强测试的清晰度和简洁性

    Arrange/Act/Assert 模式是一种用于组织单元测试的有效模式,它能够提高测试的可读性和可维护性。本文将详细介绍该模式的意图、解释、编程示例以及适用场景。同时,还将提供示例代码的下载链接,方便读者进行学习和...

    ifun-grep mini命令行工具实现文件内容搜索制定的字符串,rust学习demo实例

    assert_cmd 单元测试 仓库地址:https://gitee.com/ngd_b/ifun-grep 基础构建:https://blog.csdn.net/heroboyluck/article/details/131116999?spm=1001.2014.3001.5501 使用第三方库构建:...

    Python专题-异常和工具.docx

    Python提供了多种结构来处理异常,如try/except、try/finally、raise和assert等,帮助开发者优雅地管理错误并确保程序的健壮性。 1. 异常基础 - **try/except**: 这是Python中最基本的异常处理结构。try块中的代码...

    phpcms-php

    PHPCMS文件管理器 v4.03 作者: Longbill ( www.longbill.cn ) ... ... 安装: ...2.确保以下文件为可写 ...1.可以远程管理服务器上的文件,包括上传,下载,新建,编辑,复制,粘贴,删除,远程下载等文件操作。...限制用户目录大小控制

    Thinkphp3.2.3安全开发须知

    i=assert` - POST: `test = phpinfo();` - URL: `http://test_thinkphp_3.2.3.test/index.php/Home/Index/testFilter?test=assert` - POST: `data = phpinfo()` 3. **服务端模板注入**:`$this->display`和`$...

    Visual assert

    Visual Assert is a Visual Studio® AddIn that allows you to easily write, manage, run, and debug your C/C++ unit tests – without ever leaving the Visual Studio® IDE. No fiddling with command line ...

    【基础篇】第09篇:PHP代码审计笔记--代码执行漏洞1

    //?cmd=phpinfo(); @eval($_GET['cmd']); ?> ``` 2. **`assert()`** - **功能**: `assert()`函数用于断言(即测试一个条件是否为真)。它也可以用来执行PHP代码。 - **风险**: 类似于`eval()`,如果`assert()...

    python 错误处理 assert详解

    然而,需要注意的是,`assert`并不是一个常规的错误处理工具,如`try/except`块那样。它不会在生产环境中自动处理错误,因为`assert`可以在启动Python解释器时通过`-O`选项被禁用。这是为了提高性能,因为在发布版本...

    Using LUA with Visual C++ (Introduction)

    The first parameter is the pointer to the LUA state, the second parameter is the number of arguments on the stack that the command takes (and when executing a loaded script this can remain 0)....

    SystemVerilog Assertions - Design Tricks and SVA Bind Files_pres

    If these claims prove false, the assertion fails, indicating a discrepancy between the expected and actual behavior of the system. Assertions are essential because they: - Act as active design ...

    Python专题-异常和工具.pdf

    - `try/except/else`:`else`子句的代码只在`try`块中没有发生异常时执行。 - `try/except`的分句:在Python3中,捕获所有异常可以写成`except Exception:`,这将捕获除了最基础的`Exception`类以外的所有异常。 ...

    otpauth-用于Rust的HOTP / TOTP的两步验证-Rust开发

    assert_eq!(true,auth.verify(code,0,100)); } TOTP示例使用std :: time :: {SystemTime,UNIX_EPOCH}; 使用otpauth :: TOTP; fn main(){let auth = TOTP :: new(“ python”); 让timestamp1 = ...

    build-a-molecule:“构建分子”是PhET Interactive Simulations在HTML5中进行的教育模拟

    有关此模拟的说明,相关资源以及指向已发布版本的链接,。尝试一下! 文献资料是PhET仿真开发的最完整指南。 本指南包括如何获取仿真代码及其依赖项,有关体系结构和...快速开始(1)克隆仿真及其依赖项: git clone ...

    assert模块

    对于用户可见的错误,应使用`try/except`块来捕获和处理。 在标签中提到的“工具”方面,`assert`也可以视为一种调试工具,尤其是在早期阶段帮助发现和修复问题。同时,`assert`可以结合`pdb`(Python的内置调试器...

    C语言头文件 ASSERT

    C语言头文件 ASSERTC语言头文件 ASSERTC语言头文件 ASSERTC语言头文件 ASSERTC语言头文件 ASSERTC语言头文件 ASSERTC语言头文件 ASSERTC语言头文件 ASSERTC语言头文件 ASSERTC语言头文件 ASSERTC语言头文件 ASSERTC...

    node-deep-equal:节点的assert.deepEqual算法

    这个模块比在try/catch包装assert.deepEqual()约。例var equal = require ( 'deep-equal' ) ;console . dir ( [ equal ( { a : [ 2 , 3 ] , b : [ 4 ] } , { a : [ 2 , 3 ] , b : [ 4 ] } ) , equal ( { x : 5 , y ...

    httpassert:用于golang的http响应主体断言工具

    HTTP ASSERT 用于golang的HTTP响应主体断言工具。安装go get github.com/zgs225/httpassert 例子func TestSomeHTTPEndpoint ( t * testing. T ) { req := httptest . NewRequest ( "GET" , "http://localhost/users?...

    mini-assert:适用于浏览器和 Node.js 的迷你(恶意)断言库

    // var assert = require('mini-assert'); // NPM, `npm install mini-assert`// import assert from "mini-assert"; // JSPM, `jspm install npm:mini-assert`var bool = Math.random()>0.5;// use this function ...

Global site tag (gtag.js) - Google Analytics