0
0
Pythonprogramming~5 mins

Raising exceptions in Python - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does it mean to raise an exception in Python?
Raising an exception means telling Python that an error or unexpected situation happened. It stops normal code flow and looks for a way to handle the problem.
Click to reveal answer
beginner
How do you raise a ValueError with a custom message in Python?
Use the raise keyword followed by the exception type and message, like this:<br>
raise ValueError("This is a custom error message")
Click to reveal answer
beginner
What happens if you raise an exception but do not handle it?
If an exception is raised and not caught by any try-except block, the program stops running and shows an error message.
Click to reveal answer
intermediate
Can you raise your own custom exception class in Python?
Yes! You can create a new class that inherits from <code>Exception</code> and then raise it like any other exception.
Click to reveal answer
beginner
What is the purpose of raising exceptions in your code?
Raising exceptions helps you signal when something goes wrong, so you or other parts of the program can handle the problem properly instead of continuing with wrong data.
Click to reveal answer
Which keyword is used to raise an exception in Python?
Araise
Bthrow
Cerror
Dexcept
What will happen if you run this code?<br>
raise TypeError("Wrong type")
AThe program ignores the error
BThe program prints 'Wrong type' and continues
CNothing happens
DThe program stops and shows a TypeError with message 'Wrong type'
How do you raise a custom exception named MyError?
Araise Exception('MyError')
Bthrow MyError()
Craise MyError()
Derror MyError()
Which of these is a correct way to raise a ValueError with message 'Invalid input'?
Athrow ValueError('Invalid input')
Braise ValueError('Invalid input')
Craise 'Invalid input'
Derror ValueError('Invalid input')
If an exception is raised but not caught, what happens?
AProgram stops and shows an error message
BProgram restarts automatically
CException is ignored
DProgram continues normally
Explain in your own words what it means to raise an exception and why you might want to do it.
Think about telling your program something went wrong.
You got /4 concepts.
    Write a short Python example that raises a ValueError with a message when a number is negative.
    Use an if statement to check the number, then raise the error.
    You got /4 concepts.