In this tutorial we are going to learn :

  • Exceptions in Python
  • Handling Exceptions
  • Raising Error

 

 

Exceptions in Python

 

When we write code, we can make some mistakes in our programs and because of these mistakes, our program gives an error. That’s why we have to control it. Look at the example below. 

Example :

As you can see we have errors because of our program. Because we created a tuple with 4 items and we asked for the fifth item.

 

 

Let’s look at another example

Example :

In this program, we asked the user to type his/her age and we typed a string and our program crashed.
Because of that, we have to use exceptions to control our programs.

 

 

 

 

Handling Exceptions

 

To create an exception in Python , we use try and except keywords.

  • try   : lets you test a block of code for errors.
  • except   : lets you handle the error.

Example :

In this program, we want from the user to type a number. If the number is 0 , our program will print ” Number cannot be 0.” .
We have to use ZeroDivisionError to control it .

try:
    number = int(input("Please Enter Number : "))
    x = 100 / number
    
except ZeroDivisionError:
    print("Number cannot be 0. ") 

 

 


Raising Error


We can also choose to throw an exception if a condition occurs. To raise an exception you can use the raise keyword.

Example:

The same program with the raise keyword.

def your_age(age):
    age = int(input("Enter Your Age : "))
    if age <= 0:
        raise ValueError("Age cannot be 0 or less .")
    return 100 / Age
    

try:
    your_age(0)
    
except ValueError as age_error:
    print(age_error) 
0 0 vote
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments