Python中的用户定义异常

Python has a lot of built-in exceptions like ZeroDivisionError, IndexError, ImportError, TypeError, etc but when built-in the exception is not enough to handle our requirements then we create own customized exception. Python allows us to create our exception from the base class exception. To understand it in a better way, let's take an example that raises the error if we will try to find the square root of a negative number. Suppose, we try to find the square root of the -9 then we will get the output in the form of the imaginary number as we all know but here we will write a Python program that raises an error instead of showing the imaginary number and we will handle it by using the try-except statement.

Python有很多内置的异常,例如ZeroDivisionErrorIndexErrorImportErrorTypeError等,但是当内置的异常不足以满足我们的要求时,我们将创建自己的自定义异常 。 Python允许我们从基类异常中创建异常。 为了更好地理解它,让我们举一个如果发现负数的平方根会引发错误的示例。 假设我们尝试找到-9的平方根,然后我们将以虚数的形式获得输出,但是在这里,我们将编写一个引发错误而不是显示虚数的Python程序,我们将通过使用try-except语句来处理它。

Before going to write the Python program, we will the syntax of the try-except statement,

在编写Python程序之前,我们将使用try-except语句语法

    try:
       #statement or line of code
    except typeofError:
       #statement or line of code

Now, we will see the program in which we will create the user-defined exception to overcome the problem of imaginary number and again we handle it by using the try-except statement.

现在,我们将看到一个程序,其中将创建用户定义的异常来克服虚数的问题,然后再次使用try-except语句对其进行处理。

Program:

程序:

# creating child class from base class Exception
class Error(Exception): 
    pass   # dummy function
class InvalidNumberError(Error):
    def __init__(self,statement,s): # constructer
        self.statement=statement
        self.s=s
number=int(input('Enter a Number: '))

try:
    if number<1: # condition checking
        raise InvalidNumberError('You have entered a negative number.',number)
    else:
      print('The square root of the number:',(number)**0.5)
except InvalidNumberError as e: #user defined exception handling
    print(e.statement)

Output

输出量

RUN 1:
Enter a Number: 5
The square root of the number: 2.23606797749979

RUN 2:
Enter a Number: -5
You have entered a negative number.


翻译自: https://www.includehelp.com/python/user-defined-exception.aspx

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值