Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How continue execute program after assertion in python?

I am learning Exception in python and i have some doubt:

Can we use any name as error in raise?

like i have read when you use raise you have to define error type so can't i use any stringname as Error? like SkienaError or i have to keep in mind all the error types and have to use only those Error type names ?

    a=int(input())
if a!=10:
    raise SkienaError
else:
    print(a,"pp")

Second doubt is suppose i want user should input int but he input string so an assert pop up but i want program should continue without terminate and again ask for input until user give int type input , I don't want to use while loop here i want to know if it is possible with raise or assert in python ? like:

a=int(input())
assert type(a)==int
print(a,"hello")

So if user give str type input then is it possible program keep giving error and asking new input until input type is int.

like image 434
Eleutetio Avatar asked Oct 29 '16 22:10

Eleutetio


1 Answers

In order to make your own exception, you'll have to create it.

e.g.

class MyAppLookupError(LookupError):
'''raise this when there's a lookup error for my app'''

To continue execution after a thrown Exception, do it like this:

a = 5
try:
    assert a == 5
except AssertionError as e:
    print(e)

A try block will attempt to execute a block of code. If an exception occurs, it will execute the except block.

like image 86
Jordan McQueen Avatar answered Nov 15 '22 05:11

Jordan McQueen