Hurry! 20% Off Ends SoonRegister Now

Python Exception Handling

We are very well aware with the importance of programming languages. They are basis  for all sorts of Digital and technological advancements we have made.

Hence, since the dawn of the information age, programmers are looking for languages that can provide them variety of features. Guido von Rossum, the creator of the Python, was such programmer. He wanted to have a language that can provide all the features he wanted, for instance Scripting language, High level data type, etc.

If you would like to become a Python certified professional, then visit Mindmajix - A Global online training platform:  Python Online TrainingCourse. This course will help you to achieve excellence in this domain.

Exception Handling in Python

Python is a language that is good for projects that require quick developments. It is general purpose high level language and can be used for variety of programming problems.

Python just like other programming languages provides the method of detecting any errors. However, Python requires the exceptions (errors) to be handled at first instance before the successful execution of the program.

It is quite reasonable that practical applications of the programs may contain aspects that cannot be processed effectively by the programming language. Hence, error handling is an important and useful part of programming.

For brushing up our error handling skills, we will take a look at Exception handling. Here, in this article, we will discuss the major components of Python exception handling. To make the process easier we will first take a look at major aspects of exception handling in Python.

Also Read: Python Tutorial for Beginners

What are exceptions in Python?

Exception in python allows the user to run a program if any problems occur using conditions in except command. Python Programming language works as per the instructions of the program. Whenever there are certain aspects which Python does not understand, it shows an exception, which means in the case of Python, the exceptions are errors.

Python ceases the action whenever it encounters any exception. It only completes the execution after the exceptions are handled.  Here is an example of exception handling.

Syntax for try except else:

Try:
Print A.
Except exception
If A is exception, then execute this block.
Else
If there is no exception, then execute this block.

This syntax represents, to print A if no exception is present. Otherwise follow the instruction in exception statement. The program specifies certain conditions in case of encountering exceptions.

Instructions:

  • More than one exceptions can be used in any program.
  • Else-block can be used after the except clause, if the block in try: does not raises any exception.
  • Else-block can be used for the code that does not require try: block’s protection.
  • Generic clause can be provided to handle any exception.

Error:

>>> while True print('Hello world')
  File "", line 1
    while True print('Hello world')
                   ^
SyntaxError: invalid syntax

Here, invalid syntax represent a missing colon before print command, this program cannot be executed due to syntax error.

Related Article: Why Learn Python

Why use Exceptions? 

Exception can be helpful in case you know a code which can produce error in the program. You can put that code under exception and run an error free syntax to execute your program. This helps in preventing the error from any block which is capable of producing errors. Since exception can be fatal error, one should use exception syntax to avoid the hurdles.

Python itself contains a number of different exceptions. The reasons can vary as per the exception.

Here, we are listing some of the most common exceptions in Python.

  • ImportError: When any object to be imported into the program fails. 
  • Indexerror: The list being used in the code contains an out of range number. 
  • NameError: An unknown variable is used in the program. If the program do not contains any defined by the user and the used variable is also not pre defined in the Python, hence this error comes into play. 
  • SyntaxError: The code cannot be parsed properly. Hence it is necessary to take various precautionary measures while writing the code. 
  • TypeError: An inappropriate type of function has been used for the value. 
  • ValueError: A function has been used with correct type however the value for the function is irrelevant.

These errors are some of the most common ones and are required to be used, in case any sort of exceptions are required to be used.

Python also has assertion feature which can be used for raising exceptions. This feature tests an expression, Python tests it. If the result comes up false then it raises an exception. The assert statement is used for assertion. Assert feature improves the productivity of the exceptions in Python.

However for now, we will just focus upon raising exceptions with the use of raise statement.

Related Article: Install Python on Windows and Linux

Catching Exceptions in Python

Critical block of code which is susceptible to raise exception is placed inside the try clause and the code which handles exception is written with in except clause. If we want any particular or specific exception using- “try” clause would be helpful as we can mention several exceptions under one command.

Raising an exception is beneficial. It helps in obstructing the flow of program and returning the exception until it is handled. Raise statement can be used to raise an statement.

Example of a pseudo code:

try:    
   # do something
   pass
 
except ValueError:
   # handle ValueError exception
   pass
 
except (TypeError, ZeroDivisionError):
   # handle multiple exceptions
   # TypeError and ZeroDivisionError
   pass
 
except:
   # handle all other exceptions
   pass

Handling an Exception in Python

To handle an exception in python, try command is used. And there are certain instruction to use it,

  • The try clause is executed including a statement between try and except.
  • If no exception, the except clause is skipped and try statement is executed.
  • If exception occurred, statement under except if matches the exception then clause is executed else try statement is executed
  • If an exception occurs which does not match the exception named in the except clause, outer try statements are followed. If no handler is found, it is an unhandled exception and execution stops.
  • The block of the code that can cause an exception can be avoided by placing that block in try: block. The block in the question can then be used under except exception.

Example:

>>> while True:
...     try:
...         x = int(input("Please enter a number: "))
...         break
...     except ValueError:
...         print("Oops!  That was no valid number.  Try again...")
...

Here is another example:

try:
    num1 = 7
    num2 = 0
    print (num1 / num2)
    print(“Done calculation”)
except ZeroDivisonError:
    print(“Infinity”)

The code signifies another example of handling the exception. Here the exception is ZeroDivisionError.

Output:

Infinity

The Except Clause with No Exceptions

Though it is not considered like a good practice, but yet if it has to be done, the syntax will be

try:

print 'foo'+'qux'+ 7
except:
print' There is error'
You get the output
There is error

This type of coding is not usually preferred by programmers because it is not considered as a good coding practice. The except clause is mainly important in case of exceptions. The program has to be given certain exceptions for the smooth execution of the code. It is the main function of the except clause.

The python program containing except clause with no exception is susceptible to errors which can break the flow of the execution of the program. It is a safe practice to recognize any block susceptible to exceptions and using except clause in the case.

Here is another example
try:

   word = “python”
   print(word / 0)
except:
   print(“An error occurred”)

As you can see in the above code, there are no exceptions whatsoever. Moreover the function described in the above code is incorrect. Hence, as per the instructions, we got the following output.

Output :

An error occured

The Except Clause with Multiple Exceptions

For multiple exceptions, Python interpreter finds a matching exception, then it will execute the code written under except clause.

Except(Exception1, Exception2,…ExceptionN)

For example:

import sys
try:
d = 8
d = d + '5'
except(TypeError, SyntaxError)as e:
print sys.exc_info()

We get output as shown

(, TypeError("unsupported operand type(s) for
 +: 'int' and 'str'",), )

The usage of multiple exceptions is a very handy process for the programmers. Since, the real world execution requires some aspects which can be in deviation with analytical aspect, the exceptions are handy to use.

MindMajix Youtube Channel

Python being particularly used for the quick development projects, prevents exceptions while saving the errors at the same time.

Here is another example with multiple exceptions.

try:    

  variable = 8
     print(variable + “hello”)
     print(variable / 4)
except ZeroDivisonError:
     print(“Divided by zero”)
except (ValueError,TypeError):
     print(“Error occurred”)

Code given above shows examples of multiple exceptions. The types of error in this program have been excepted(Except here means that the invalid operations that we want to execute are skipped and final message is printed that we want to get printed) and result can be seen below. Since the variable 10 cannot be added to the text ‘hello’ it is quite obvious to have the exceptions, in the case.

Output:

>>>
Error occurred
>>>

The result as expected is “Error occurred”.

The try-finally Clause

There are certain guidelines using this command, either define an “except” or a “finally” clause with every try block. Also else and finally clauses cannot be used together. Finally clause is particularly useful when  the programmer is aware with the outcome of the program.

Generally, it is seen that the else clause is helpful for the programmers with not much expertise in the programming. But when it comes to error correction and termination, this clause is particularly helpful.  

For example:

try:
foo = open ( 'test.txt', 'w' )
foo.write ( "It's a test file to verify try-finally in exception handling!!")            
print 'try block executed'
finally:
foo.close ()
print 'finally block executed'

Output:

try block executed
finally block executed

Another example can be like

try:
   f = open("test.txt",encoding = 'utf-8')
   # perform file operations
finally:
   f.close()

“Finally” is a clause to ensure any code to run without any consequences. Final statement is always to be used at the bottom of ‘try’ or ‘except’ statement. The code within a final statement always runs after the code has been executed, within try po even in ‘except’ blocks.

One more example will make it clearer.

try:

 print(“Hello”)
   print(1/0)
except ZeroDivisonError:
   print(“Divided by zero”)
finally:
   print(“This is going to run anyway”)

As this program makes it clear that the statement “The program is going to run anyway” which is under the “finally” clause is always executed not depending upon the outcome of the code.

Output:

Hello
Divided by Zero
This is going to run anyway

This output shows exactly the same thing.

[ Learn About Python Classes and Objects ]

Argument of an Exception in Python

Arguments provide a useful way of analyzing exceptions with the interactive environment of Python. If the programmer is having a number of arguments which are to be used in the program, then the programmer can help in more effective results with ‘except’ clause. Here:

def print_sum_twice(a,b):
     print(a + b)
     print(a + b)
print_sum_twice(4,5)

In this program, the program has instructed the python print the sum twice. There are two conditions that have been specified in the code. Please note that the arguments are enclosed in the parenthesis.

Output:

>>>
9
9
>>>

Raising Exceptions in Python

By raising a keyword forcefully we can raise an exception, its an alternative and manual method of raising an exception like exceptions are raised by Python itself.

We can also optionally pass in value to the exception to clarify why that exception was raised. Raising an exception or throwing it is a manual process and it quite helpful when the programmer is well aware with the potential exceptions.

Manual exceptions increase the affectivity in the execution of the program. The manual exceptions save Python from encountering any exceptions itself. Hence, smoothing the execution of the program.

If you want to understand the exception specifically, here is an example.

If you are a programmer and you are well aware with the program you are dealing with, has something that the Python might just not be able to understand. In this case you will like flag that block of code because you understand the significance of that code, so that you can exploit the Python’s capability of using it for quick project development and then deal with that block later.

Raising Exception in Python Example:

>>> raise KeyboardInterrupt
Traceback (most recent call last):
...
KeyboardInterrupt
 
>>> raise MemoryError("This is an argument")
Traceback (most recent call last):
...
MemoryError: This is an argument
 
>>> try:
...     a = int(input("Enter a positive integer: "))
...     if a <= 0:
...         raise ValueError("That is not a positive number!")
... except ValueError as ve:
...     print(ve)
...    
Enter a positive integer: -2
That is not a positive number!

Frequently asked Python Interview Questions & Answers

User-Defined Exceptions in Python

Exception classes only function as any regular class. However some simplicity is kept in classes to provide a few attributes improving the efficiency of the exception handling in Python. These attributes can then further be used for extraction by handlers in case of the exceptions.

During the creation of any module it is an optimal process to have a base class for exceptions which are defined particularly by that module. Subclasses can be used for creating error conditions in case of any specific exception.

Python itself offers a variety of exceptions that can be used during the programming by programmers. However, the python also offers also offers full freedom to create any manual exceptions.These exceptions increase the extent of productivity in Python.

class Error(Exception):
    """Base class for exceptions in this module."""
    pass
 
class InputError(Error):
    """Exception raised for errors in the input.
 
    Attributes:
        expression -- input expression in which the error occurred
        message -- explanation of the error
    """
 
    def __init__(self, expression, message):
        self.expression = expression
        self.message = message
 
class TransitionError(Error):
    """Raised when an operation attempts a state transition that's not
    allowed.
 
    Attributes:
        previous -- state at beginning of transition
        next -- attempted new state
        message -- explanation of why the specific transition is not allowed
    """
 
    def __init__(self, previous, next, message):
        self.previous = previous
        self.next = next
        self.message = message
 

Most exceptions are defined with names that end in “Error”, similar to the naming of the standard exceptions. Standard modules offer their own exceptions for defining any specific error for functions they define.

This is it what we have for ‘Basics of Exception Handling in Python’. If you have any suggestions that we can add in this article to make it more easier for beginners, please do share with us in the comment box.

Happy Coding!

If you are interested to learn Python and to become an Python Expert? Then check out our Python Certification Training Course at your near Cities.

Python Course ChennaiPython Course BangalorePython Course DallasPython Course Newyork

These courses are incorporated with Live instructor-led training, Industry Use cases, and hands-on live projects. This training program will make you an expert in Python and help you to achieve your dream job.

Explore Python Sample Resumes! Download & Edit, Get Noticed by Top Employers!Download Now!

Job Support Program

Online Work Support for your on-job roles.

jobservice

Our work-support plans provide precise options as per your project tasks. Whether you are a newbie or an experienced professional seeking assistance in completing project tasks, we are here with the following plans to meet your custom needs:

  • Pay Per Hour
  • Pay Per Week
  • Monthly
Learn MoreGet Job Support
Course Schedule
NameDates
Python TrainingDec 24 to Jan 08View Details
Python TrainingDec 28 to Jan 12View Details
Python TrainingDec 31 to Jan 15View Details
Python TrainingJan 04 to Jan 19View Details
Last updated: 29 Jun 2024
About Author

Anjaneyulu Naini is working as a Content contributor for Mindmajix. He has a great understanding of today’s technology and statistical analysis environment, which includes key aspects such as analysis of variance and software,. He is well aware of various technologies such as Python, Artificial Intelligence, Oracle, Business Intelligence, Altrex, etc. Connect with him on LinkedIn and Twitter.

read less
  1. Share:
Python Articles