Menu
Coddy logo textTech

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 icon

Challenge

Easy

A 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 here

All lessons in Exception Handling in Python