Python Tutorial @ Home

Python Exception Handling

Python Exception
Common Exceptions
The problem without handling exceptions
Exception handling in python
The except statement with no exception
The except statement using with exception variable
Declaring Multiple Exceptions
The try…finally block
Raising exceptions

Python Exception Handling

Raising exceptions

An exception can be raised forcefully by using the raise clause in Python. It is useful in that scenario where we need to raise an exception to stop the execution of the program.
It helps us to define user defined checks

The syntax to use the raise statement is given below.

Syntax
raise Exception_class,<value>

try:    
    age = int(input("Enter the age:"))    
    if(age<18):    
        raise ValueError   
    else:    
        print("the age is valid")    
except ValueError:    
    print("The age is not valid")   

Output:
Case:1
Enter the age:15
The age is not valid

Case:2
Enter the age:25
the age is valid

Example :Raise the exception with message

try:
    num = int(input("Enter a positive integer: "))  
    if(num <= 0):  
# we can pass the message in the raise statement  
        raise ValueError("That is  a negative number!")  
    else:
        print("number is ",num)
except ValueError as e:  
    print(e)  

Output:
Case:1
Enter a positive integer: 25
number is 25

Case:2
Enter a positive integer: -143
That is a negative number!

Example:
Write a python program to take input for 2 numbers calculate and print their sum.
conditions: number should be >=0

try:
    a=int(input("Enter 1st nos"))
    b=int(input("Enter 2nd nos"))
    if(a<0):
        raise ValueError("First value is invalid")
    if(b<0):
        raise ValueError("Second value is invalid")
    c=a+b
    print("Sum = ",c)

except ValueError as e:
    print("Error :")
    print(e)

Output:
Case:1
Enter 1st nos 10
Enter 2nd nos 20
Sum = 30

Case:2
Enter 1st nos -25
Enter 2nd nos 63
Error :
First value is invalid

Case:3
Enter 1st nos 24
Enter 2nd nos -12
Error :
Second value is invalid

Visitor Counter

0051146