Exception Handling in Python

Exception Handling

What is Exception

While executing a program sometimes the normal flow of events may get disrupted if there is a situation that Python is not able to cope with. In such a scenario it will raise and exception. Exception is nothing but a Python object that indicates that the execution of the program was disrupted due to some error. If the exception is not handled properly then the program will be terminated.

Some of the common exceptions encountered in Python are as follows:
1. SystemExit: This exception is raised by a sys.exit() function.
2. ArithematicError: Occurs when there is a problem with arithematic calculation.
3. IOError: When the program faces problem in opening a file.
4. ValueError: when an invalid argument is passed to a function.

Python has defined a number of exceptions and the ones mentioned on top are just a few of them. However you can deal with exceptions with the help of try and except blocks

Whenever you write a complicated code that can create error you must put that code in try block as shown below:

try:
     code
except:
     code

As you can see in the syntax above, if there is any error encountered in the code written in the try block then the system will straight away go to except block and execute the code written there. Now let’s have a look at an example

try:
    print("let's divide a number by zero")
    print(str(1/0))
except:
    print("System has encountered an error please check your code")

Download the code Run the code

Now let’s try another example:

try:
    print("let's carry out division")
    a = input("enter the first number: ")
    b = input("enter the first number: ")
    print(a/b)      
          
except:
    print("System has encountered an error please check your code")

Download the code Run the code

The problem with the code above is that input statement provides value in string and we have to first convert the numbers to string in order to print them. Following code will not throw exception.

try:
    print("let's carry out division")
    a = input("enter the first number: ")
    b = input("enter the first number: ")
    print((int(a)/int(b)))      
          
except:
    print("System has encountered an error please check your code")

Download the code Run the code

<<< Python functions with multiple argumentsSets in Python >>>
Copyright 2005-2016 KnowledgeHills. Privacy Policy. Contact .