Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
+2 votes
3 views
in Python by (3.9k points)
I want to raise an exception in Python and in future want to detect it using an except block, Can someone tell me how to do it?

3 Answers

+2 votes
by (2k points)
edited by

You can use AssertionError to perform this command, follow up with the syntax given below:

if 0 < diameter <= length:
    #Do something.
elif length< diameter:
    #Do something.
else:
    raise AssertionError("Unexpected value of 'diameter'!", diameter)

If you are looking for upskilling yourself in python you can join our Python Certification and learn from an industry expert.

+2 votes
by (10.9k points)
edited by

There are four different syntaxes for raising exceptions in Python 3-

1.Raise exception

 try:

        raise ValueError

    except ValueError as exp:

        print ("Hello", exp)    

 2.raise exception (args)try:

        raise ValueError("I have raised an Exception")

    except ValueError as exp:

        print ("Hello", exp)     

3.Raise

This statement is used to re-raise the last exception.

def somefunction():

    print("some cleaning")

x=10

y=0 

result=None

try:

    result=x/y

    print(result)

except Exception:          

 somefunction()           

    raise        

4. raise exception(args) from original_exception

An exception raised in response of another exception which contains the details of the original exception.

 class MyCustomException(Exception):

pass

x=10

y=0

reuslt=Nonetry:

    try:

        result=x/y

 except ZeroDivisionError as exp:

        print("ZeroDivisionError -- ",exp)

        raise MyCustomException("Zero Division ") from exp

except MyCustomException as exp:

        print("MyException",exp)

        print(exp.__cause__)

0 votes
by (106k points)

You can use the below-mentioned code to manually raise the error:-

if 0 < distance <= RADIUS:

    #Do something.

elif RADIUS < distance:

    #Do something.

else:

    raise AssertionError("Unexpected value of 'distance'!", distance)

You can use the following video tutorials to clear all your doubts:-

...