简体   繁体   中英

How to make user-defined exceptions in python?

I want to Raise Multiple User-Defined Exceptions

For example -

  • incase of an invalid parameter passed to function raise ParameterException

  • incase of invalid something raise CertainExceptions and so on.

How can I do something like that in Python?


class SomeException(Exception):
    pass

try:
    print('zzz')
    raise SomeException
except ValueError as ve:
    print('a')
except SomeException as se:
    print('b')
except:
    print("c")

# print
zzz
b

Consider the program below.

Program 1:

# this program would keep prompting the user for an integer input.
while True:
    a=int(input("Enter integer: "))
    b=int(input("Enter another integer: "))
    print(a/b)

Run the program and keep inputting. If everything is fine, it will print the division of the two integers. Now Case 1: what if you input a random string? Case 2: Or what if you input 0 at the place of b variable?

Feel free to test it. You would see that, i) Case 1 raises ValueError exception ii) Case 2 raises ZeroDivisionError exception

Now, you need to handle these exceptions. How can you do that? Here's how:

Program 2:

# this program handles ValueError and ZeroDivisionError exceptions
while True:
    try:
        a=int(input("Enter integer: "))
        b=int(input("Enter another integer: "))
        result=a/b
    except ValueError:
        print("Input is not integer.")
    except ZeroDivisionError:
        print("Division by 0 is not supported.")
    else:
        print(result)

    print("\n")

Besides, you can handle all exceptions like this:

Program 3:

while True:
    try:
        a=int(input("Enter integer: "))
        b=int(input("Enter another integer: "))
        result=a/b
    except Exception:
        print("An error occured.")
    else:
        print(result)

    print("\n")

In case of user-defined exceptions, do it like this:

class MyException(Exception):
    pass

while True:
    a=int(input("Enter integer: "))
    b=int(input("Enter another integer: "))
    if b==0:
        raise MyException

    print("\n")

Later catch them like you want.

Program 3 is not a good practice. Never pass errors silently. You can make use of python's Exception class by subclassing it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM