1

For example in this code, I want my script behavior this way.

when run to b=a[2], or any line will raise an exception, and no matter what is the exception. I want the script stop, and raise a customized red error message like: 'LOL!!!'

How to implement that?

try:
    a = [1,2]
    b = a[2]
except:
    raise something

2 Answers 2

5
try:
    a = [1,2]
    b = a[2]
except IndexError:
    raise Exception('LOL!')

This works because the stament a[2] throws an IndexError. There are only 2 elements in a, and a[2] fetches the third (counting from zero).

... Alright...

class YourCustomException(Exception):
    pass

try:
    a = [1,2]
    raise YourCustomException('LOL')
except YourCustomException:
    print('NOW WHAT?')
Sign up to request clarification or add additional context in comments.

1 Comment

thank you. But it's not the answer I need. I mean, the Exception are not able to predict. I need a method to raise my custom exception message, and no matter what it is the original exception.
0

You should read about raising exception at https://docs.python.org/2/reference/simple_stmts.html#raise

Exception hirearchy is https://docs.python.org/2/library/exceptions.html#exception-hierarchy

Here is your required answer,

try:
    a = [1,2]
    b = a[2]
#except Exception:
except IndexError: 
    raise Exception("Lol")

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.