Fundamentals of Try and Except in Python – Have a Look.

Today, we’ll learn the fundamentals of Python Try and Except statements. In Python, we use these programming constructs to implement exception handling.

Exception handling is very critical for creating robust and stable applications. And it encourages programmers to write clean, readable and error-free code.

You’ll all accept that each one of us may leave errors while writing programmable code. After all, we are humans. Sometimes we make a syntactical mistake or provide a wrong input to the program. Also, a program may fail if it needs a network resource which is not available. Even it may face out of memory and similar errors.

Some of these errors may cause the program to terminate abruptly. Since none of us want a program to behave nasty, so we make arrangements to handle such situations. With the help of Python exception handling, we can manage the above issues and avoid intermittent failures of our code. The most common way to do it is by creating a python try-except block.

Python Try and Except Fundamentals.

Python try except fundamentals

[Python try except else finally…]

First of all, we have to understand the difference between an error and the exception. Consequently, we’ll teach you the essentials of Python exception handling.

The difference between an error and the exception.

What is Error?

The error is something that goes wrong in the program, e.g. like a syntactical error.

It occurs at compile time. Let’s see an example.

if a<5
File "<interactive input>", line 1
    if a < 5
           ^
SyntaxError: invalid syntax

 

What is Exception?

The errors also occur at runtime, and we know them as exceptions. An exception is an event which occurs during the execution of a program and disrupts the normal flow of the program’s instructions.

In general, when a Python script encounters an error situation that it can’t cope with, it raises an exception.

When a Python script raises an exception, it creates an exception object. Usually, the script handles the exception immediately. If it doesn’t do so, then the program will terminate and print a traceback to the error along with its whereabouts.

>>> 1 / 0
Traceback (most recent call last):
 File "<string>", line 301, in run code
 File "<interactive input>", line 1, in <module>
ZeroDivisionError: division by zero

 

How to use Python try/except clause?

Like many languages, in Python, a try statement is available for exception handling.

In every try block, there is a piece of code which can raise an exception. And the code that handles the exception, we place in the except clause.

Following is the syntax of a Python try-except-else> block.

try:
	You do your operations here;
	......................
except ExceptionI:
	If there is ExceptionI, then execute this block.
except ExceptionII:
	If there is ExceptionII, then execute this block.
	......................
else:
	If there is no exception then execute this block.

 

Have a look – 30 Python Interview Questions for Beginners.

 

Checklist to handle an exception in Python.

Here is a checklist for using the Python try statement effectively.

  • A single try statement can have multiple except statements depending on the requirement. In this case, a try block contains statements that can throw different types of exceptions.
  • We can also add a generic except clause which can handle all possible types of exceptions.
  • We can even include an else clause after the except clause. The code in the else block will execute if the code in the try block doesn’t raise any exception.

 

Python exception handling # example-1.

Let’s take a sample code to understand the use of Python try-except.

try:
   fob = open("test", "w")
   fob.write("This is my test file for exception handling!!")
except IOError:
   print "Error: can\'t find the file or read data"
else:
   print "Write operation is performed successfully on the file"
   fob.close()

The above code produces the following output.

>>Write operation is performed successfully on the file.

 

Python exception handling # example-2.

Let’s take another example in which we are trying to open a file in the READ mode. Then, we’ll perform a WRITE operation on it. Upon execution, it’ll throw the following exception.

try:
   fob = open("test", "r")
   fob.write("It's my test file to verify exception handling in Python!!")
except IOError:
   print "Error: can\'t find the file or read data"
else:
   print "Write operation is performed successfully on the file"

The above code produces the following output.

>>Error: can't find file or read data

 

How to define except Clause with No Exceptions?

Defining except clause with no exceptions enables it to handle all types of exceptions. However, neither it’s a good programming practice nor does anyone recommend it.

It is because that such a Python try-except block can handle all types of exceptions. But it’ll not help the programmer to find which type of exception caused the issue.

If you still want to use it, then refer the following code.

Python exception handling # example-3.

try:
   You do your operations here;
   ......................
except:
   If there is any exception, then execute this block.
   ......................
else:
   If there is no exception then execute this block.

 

How to use except Clause with Multiple Exceptions?

We can define multiple exceptions with the same except clause. It means that if the Python interpreter finds a matching exception, then it’ll execute the code written under the except clause.

In short, when we define except clause in this way, we expect the same piece of code to throw different exceptions. Also, we want to take the same action in each case.

Please refer the below example.

Python exception handling # example-4.

try:
   You do your operations here;
   ......................
except(Exception1[, Exception2[,...ExceptionN]]]):
   If there is any exception from the given exception list,
   then execute this block.
   ......................
else:
   If there is no exception then execute this block

 

How to use Python try-finally clause?

With try block, we also have the option to define the “finally” block. This clause allows defining statements that we want to execute, no matters whether the try block has raised an exception or not.

This feature usually comes in the picture while releasing external resources.

Here is the coding snippet for help.

try:
   You do your operations here;
   ......................
   Due to any exception, this may be skipped.
finally:
   This would always be executed.
   ......................

 

Python exception handling # example-5.

One very important point is that we can either define an “except” or a “finally” clause with every try block. You can’t club these together. Also, you shouldn’t use the “else” clause along with a “finally” clause.

Let’s take an example to get more clarity.

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

If the exception doesn’t occur, then you’ll see the following output.

>>try block executed
>>finally block executed

 

Python exception handling # example-6.

Suppose we open the file in the READ mode and then try to perform a write operation on it. In such a situation, below code will help to handle the exception.

try:
    fob = open('test', 'r')
    try:
        fob.write("It's my test file to verify try-finally in exception handling!!"
                  )
        print 'try block executed'
    finally:
        fob.close()
        print 'finally block executed to close the file'
except IOError:
    print "Error: can\'t find file or read data"

 

In this case, the interpreter will raise an exception and the following output will get displayed.

>>finally block executed to close the file
>>Error: can\'t find file or read data

When some code causes an exception in a try block, the execution immediately passes to the “finally” block. After all the statements in the “finally” block gets executed, the exception resumes to the “except” block for execution. But there must present a next higher layer of the “try-except” statement.

 

How to raise an exception and provide arguments?

We can forcefully raise an exception using the raise keyword. We can also optionally pass values to the exception and specify why this exception should occur. Here is the syntax for calling the “raise” method.

raise [Exception [, args [, traceback]]]

where,

  • The exception is the name of the exception.
  • The “args” is optional and represents the value of the exception argument.
  • The final argument, traceback, is also optional and if present, is the traceback object used for the exception.

Let’s take an example to clarify this.

Python exception handling # example-7.

>>> raise MemoryError
Traceback (most recent call last):
...
MemoryError
 
>>> raise MemoryError("This is an argument")
Traceback (most recent call last):
...
MemoryError: This is an argument
 
 
>>> try:
      a = int(input("Enter a positive integer value: "))
     if a <= 0:
            raise ValueError("This is not a positive number!!")
    except ValueError as ve:
      print(ve)
 
 
Following Output is displayed if we enter a negative number:
  
Enter a positive integer: –5
 
This is not a positive number!!

 

User-Defined Exceptions.

How to define a custom exception in Python?

We can add user-defined exceptions by creating a new class in Python. The trick here is to derive the custom exception class from the base exception class. Most of the built-in exceptions use the same technique to enforce their exceptions.

Create an exception class in Python.

>>> class UserDefinedError(Exception):
...     pass
 
>>> raise UserDefinedError
Traceback (most recent call last):
...
__main__.UserDefinedError
 
>>> raise UserDefinedError("An error occurred")
Traceback (most recent call last):
...
__main__.UserDefinedError: An error occurred

In the above code snippet, you can see that we have created a user-defined exception class, the “UserDefinedError“. It is using the base Exception class as the parent. Hence, the new user-defined exception class will raise exceptions as any other exception class does i.e. by calling the “raise” statement with an optional error message.

Let’s take an example.

Python exception handling # example-8.

In this example, we will show how to raise an user-defined exception and catch errors in a program. Also, in the sample code, we will ask the user to enter an alphabet again and again until he enters the stored alphabet only.

For help, the program provides a hint to the user so that he can figure out the correct alphabet. Also, he can check whether his guess is greater or less than the stored alphabet.

#define Python user-defined exceptions
class Error(Exception):
   """Base class for other exceptions"""
   pass
 
class InputTooSmallError(Error):
   """Raised when the entered alpahbet is smaller than the actual one"""
   pass
 
class InputTooLargeError(Error):
   """Raised when the entered alpahbet is larger than the actual one"""
   pass

#our main program
#user guesses an alphabet until he/she gets it right
 
#you need to guess this alphabet
alphabet = 'm'
 
while True:
   try:
       apb =  raw_input("Enter an alphabet: ")
       if apb < alphabet:
           raise InputTooSmallError
       elif apb > alphabet:
           raise InputTooLargeError
       break
   except InputTooSmallError:
       print("The entered alphabet is too small, try again!")
       print('')
   except InputTooLargeError:
       print("The entered alphabet is too large, try again!")
       print('')
 
print("Congratulations! You guessed it correctly.")

Example-8# Run with multiple tests data.

Let’s test this program by supplying different inputs.

Enter an alphabet: s
This value is too large, try again!
 
Enter an alphabet: a
This value is too small, try again!
 
Enter an alphabet: l
This value is too small, try again!
 
Enter an alphabet: p
This value is too large, try again!
 
Enter a number: m
Congratulations! You guessed it correctly.

Thus you can see that we have defined a base class called Error here in this program. The two exceptions (“InputTooSmallError” and “InputTooLargeError“) that are raised by our program are derived from this class. It’s the standard way to define user-defined exceptions in Python programming.

List of Python Built-in Exceptions.

ExceptionCause of Error
AirthmeticErrorFor errors in numeric calculation.
AssertionErrorIf the assert statement fails.
AttributeErrorWhen an attribute assignment or the reference fails.
EOFErrorIf there is no input or the file pointer is at EOF.
ExceptionIt is the base class for all exceptions.
EnvironmentErrorFor errors that occur outside the Python environment.
FloatingPointErrorWhen floating point operation fails.
GeneratorExitIf a generator’s <close()> method gets called.
ImportErrorWhen the imported module is not available.
IOErrorIf an input/output operation fails.
IndexErrorWhen the index of a sequence is out of range.
KeyErrorIf the specified key is not available in the dictionary.
KeyboardInterruptWhen the user hits an interrupt key (Ctrl+c or delete).
MemoryErrorIf an operation runs out of memory.
NameErrorWhen a variable is not available in local or global scope.
NotImplementedErrorIf an abstract method isn’t available.
OSErrorWhen a system operation fails.
OverflowErrorIf the result of an arithmetic operation exceeds the range.
ReferenceErrorWhen a weak reference proxy accesses a garbage collected reference.
RuntimeErrorIf the generated error doesn’t fall under any category.
StandardErrorIt is a base class for all built-in exceptions except <StopIteration> and <SystemExit>.
StopIterationThe <next()> function has no further item to be returned.
SyntaxErrorFor errors in Python syntax.
IndentationErrorWhen indentation is not proper.
TabErrorFor inconsistent tabs and spaces.
SystemErrorWhen interpreter detects an internal error.
SystemExitThe <sys.exit()> function raises it.
TypeErrorWhen a function is using an object of the incorrect type.
UnboundLocalErrorIf the code using an unassigned reference gets executed.
UnicodeErrorFor a Unicode encoding or decoding error.
ValueErrorWhen a function receives invalid values.
ZeroDivisionErrorIf the second operand of division or modulo operation is zero.

Summary – Python Try and Except Fundamentals.

Most of the time, we aim to discover a topic that can help our readers in their work. Also, we intend to teach them skills that matter the most in their job profile. That’s why we covered this tutorial on using Python try-except constructs.

It would be great to hear from you if this post helped you in learning Python. So do let us know about your experience.

Also, you can submit a request for any topic of your choice. We’ll include it in our plan and add to the priority list.

If you liked the post, then please don’t miss to share it with friends and on social media (facebook/twitter).

Teaching is the best asset that a person should share without any cost.

Keep Learning,

TechBeamers.

4 Comments

  1. belen Reply
    • Meenakshi Agarwal Reply
  2. Srinivas Kotaru Reply
    • Meenakshi Agarwal Reply