zoukankan      html  css  js  c++  java
  • 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.
  • 相关阅读:
    基础篇
    模块,包
    初识面向对象
    linux在线安装jdk
    热点链接(img map area)
    oracle temp 临时表
    ajax基础代码
    Java编译执行带包名java文件
    oracle spool 用法小结
    Hadoop NameNode safemode
  • 原文地址:https://www.cnblogs.com/jfdwd/p/11086675.html
Copyright © 2011-2022 走看看