Raising an Exception
Lesson 11 of 16 in Coddy's Exception Handling in Python course.
'raise' Keyword:
You can raise any Exception (Built-in + Custom) by using 'raise' keyword.
You can pass message inside raised Exception that designates the problem.
syntax: raise [ExceptionName](optional_message)
try:
n = int(input("Enter the number for factorial:"))
if n < 0:
raise ValueError("Number cannot be negative")
#factorial code here
except Exception as obj:
print(obj)In above example, raise statement will be executed if user enters number less than 0. This statement will raise ValueError and control goes to except block. "Number cannot be negative" will be passed to obj and got printed on console.
Challenge
EasyA function will take mobile number (string) as input.
Raise ValueError if any character is not digit and length is not equal to 12 digits. Print "Invalid" on console, else "valid".
Try it yourself
def contact_details(mobile):
#your code goes hereAll lessons in Exception Handling in Python
4Customization/best practices
Customize Tracebacks3User-defined Exceptions
Types of ExceptionsRaising an ExceptionUser Defined ExceptionException Handling Exercise- 1Exception Handling Example-2Exception Handling Example-3