Reputation: 139
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.
Upvotes: 7
Views: 12626
Reputation: 3298
This might also work for your situation. The function Assert()
prints a message sTxt
in red color, if the Boolean input bCond
is False
and interpreter continues execution:
RED, END = '\033[91m', '\033[0m'
printRed = lambda sTxt: print(RED + sTxt + END)
Assert = lambda bCond=False, sTxt='': printRed(sTxt) if not bCond else None
Upvotes: 0
Reputation: 787
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.
Upvotes: 10