zoukankan      html  css  js  c++  java
  • python 异常处理

    1、错误:代码不符合编程规范,无法被识别与执行。 

    2、异常:语法正确,可以被执行,但在执行过程中遇到了错误,抛出异常。

    python 处理异常语句的模板如下:

    try:
        #可能发生的异常语句块
        
    except:
        #执行异常处理相关代码
    
    else:
        #如果没有异常执行此段代码
    
    finally:
        #不管有没有异常,都执行此段代码

    示例:

    while True:
        try:
            x=int(input("please type a number:"))
    
        #万能的异常处理:抛出异常
        except Exception as e:
            print(e)
        else:
            print(x)
        finally:
            print("done")
    def f(n):
        if n>50:
            #主动抛出异常
            raise Exception("bigger")
    try:
        n = int(input())
        f(n)
        
    except Exception as e:
        print("no",e)
        
    else:
        print(n)
        
    finally:
        print("done")

    自定义异常:

    class MyError(Exception):
        def __init__(self,value):
            self.value=value
        def __str__(self):
            return repr(self.value)
    
    try:
        num = input("type an number:")
        if not num.isdigit():
            raise MyError(num)
        
    except MyError as e:
        print("MyError:type a number,you type is :",e.value)
    
    else:
        print(num)
    
    finally:
        print("Done")
  • 相关阅读:
    SpringMVC_04重定向和转发
    Spring事务声明
    SpringMVC_02_RequestMapping
    SpringMVC_01_初识
    Spring通过mybatis操作数据库
    SpringMVC_03_RestFul
    SpringMVC_05_json数据传输
    退役
    2017ICPC青岛 J.Suffix
    版本不兼容问题(未找到程序集)
  • 原文地址:https://www.cnblogs.com/yijierui/p/13911160.html
Copyright © 2011-2022 走看看