7

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.

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

8 Comments

i tried what you said but failed check out what i am trying to do : paste.ofcode.org/brZxC42zRerVbmwSRpkrv4
except error is a syntax error. you want except AssertionError
i can't define anyname ? i have to use specially "AssertionError" as keyword ??
assert is a special keyword that raises an Exception of subctype AssertionError. You can write except Exception or except AssertionError. If you want to make your own, you'll have to write an Exception class for it.
ok sure i tried again what you said but its not asking again for int if i am giving str type input : paste.ofcode.org/6SD7uwX6FNrvgppHxF5vEW
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.