Python Try…Except

 There’s always a possibility that an error can occur when a program is running in python which can cause an abrupt halt. The error is called an exception. Since Python won’t tell you about syntax errors, it’ll bring the program to an unexpected stop which might be detrimental to both the programmer and user. However, there is a remedy to avoid such unpleasant conditions. Instead of an emergency halt, you can deploy the try… except statement to avert the problem.

Python try… Except statements are a vital asset to carefully implement when coding. The try-except statement can handle exceptions.

At the end of this page, you’ll be fully equipped with the following:

  • What Is Python try-Except
  • The Else Clause
  • Python Try… Except
  • Try Finally

Afterward, you’ll be all good to carry out important activities in the try… except statement

What is Python Try…Except?

The Python Try…Except statement helps you to detect an error in a block of codes and handle them to avoid an error raise. Further light, if an error occurred in Python while running a program it is called an exception.

In this way, If an exception occurs the type of exception will be shown and it will be dealt with else the program will crash. Before we delve into how to handle the exception in python let’s see some Common exception errors.

Some of the common Exception Errors are

  • IOError: Is short for Input/Output error. IOError indicates the file can’t be opened
  • KeyboardInterrupt: This is when an unrequired key is pressed by the user.
  • ValueError: when a wrong argument is added to a built-in function.
  • EOFError: when the End-Of-File is reached without reading any data
  • ImportError: the module was not found
  • MemoryError: an operation is out of memory.
  • NameError: a variable is not present in the local and global scope.
  • OverflowError: An arithmetic operation is too large to be operated.
  • IndentationError: An incorrect indentation occurrence.
  • TabError: inconsistent tabs present in indentation.
  • ValueError: a function gets an argument of the correct type but improper value.

The try block is used to detect any of the above exceptions(errors). i.e the try code will execute when there are no errors in the program. Otherwise, the code inside the except block will execute to handle the problems encountered. The syntax for the Try… Except is: try:

    # Some Code

except:

    # Executed if an error in the

    # try block

Before we see some code examples, let’s see How try() works

  • Initially, the try code is executed
  • If there is no exception in the process of running the program, then only the try code will run till the end of the block.
  • If in the process, any exception is detected, the except clause will run.
  • If the exception occurs, but the except clause within the code couldn’t handle it, it is passed on to the outer try statements. If the exception is left unhandled, then the execution stops.
  • A try statement can have more than one except clause

Example:

Python Input

# Python code to illustrate
# working of try()
def divide(x, y):
    try:
        # Floor Division : Gives only Fractional Part as Answer
        result = x // y
        print("Yeah ! Your answer is :", result)
    except ZeroDivisionError:
        print("Sorry ! You are dividing by zero ")
# Look at parameters and note the working of Program
divide(9, 2)

Output:


Yeah ! Your answer is : 4

In the above returns, there is no exception in the program, so the try executes.

Example 2:

Python Input

# Python code to illustrate
# working of try()
def divide(x, y):
    try:
        # Floor Division : Gives only Fractional Part as Answer
        result = x // y
        print("Yeah ! Your answer is :", result)
    except ZeroDivisionError:
        print("Sorry ! You are dividing by zero ")
# Look at parameters and note the working of Program
divide(9, 0)

Output:

Sorry ! You are dividing by zero

The returns above are an exception so the clause block will run

Else Clause

When the try block does not raise an exception, the code will enter the else code block. The else block must be present in the try-except after all the except clauses

The syntax for the else block: try:

    # Some Code

except:

    # Executed if an error in the

    # try block

else:

    # execute if no exception

Python Input

# Program to depict else clause with try-except
# Function which returns a/b
def AbyB(a , b):
    try:
        c = ((a+b) // (a-b))
    except ZeroDivisionError:
        print ("a/b result in 0")
    else:
        print (c)
# Driver program to test the above function
AbyB(2.0, 3.0)
AbyB(3.0, 3.0)

Output:


-5.0
a/b result in 0

Python try…finally

The try statement can be mixed with the finally-clause and the finally-clause executes no whether there are exceptions or not. The final clause is used to give the external resources.

For instance, we might be connected to a remote data connection or a Graphical User Interface (GUI). The truth is to conclude the task done, you have to disconnect and clean up the program before it comes to a stop.

The drive home point is that all the end actions of disconnecting and cleaning up are performed in the finally-clause to guarantee execution.

The syntax for try…finally is

try:
    # Some Code
except:
    # Executed if an error in the
    # try block
else:
    # execute if no exception
finally:
    # Some code .....(always executed)

Example:

Python Input

# Python program to demonstrate finally
# No exception Exception raised in a try block
try:
    k = 5//0 # raises divide by zero exception.
    print(k)
# handles zerodivision exception   
except ZeroDivisionError:  
    print("Can't divide by zero")
finally:
    # this block is always executed
    # regardless of exception generation.
    print('This is always executed')
Output
Can't divide by zero

This is always executed

Summary

The Python try…except statement helps you to detect an error in a block of codes and handle them to avoid an error raise. Further light if an error occurred in Python while running a program it is called an exception.

the try block is used to detect any of the above exceptions(errors). i.e the try code will execute when there are no errors in the program.

By the end of this page you’ve learned the following:

  • What is PythonTry… Except
  • The Else clause
  • Python Try… Except
  • Try finally

It doesn’t take years or even a year to master the Python program. You can master the Python Language within hours. However, the speed at Which you grasp things is determined by the level of concentration. Give it all it takes and focus. For a helping hand, see the Python Tutorials. Good luck Coding!

Pramod Kumar Yadav is from Janakpur Dham, Nepal. He was born on December 23, 1994, and has one elder brother and two elder sisters. He completed his education at various schools and colleges in Nepal and completed a degree in Computer Science Engineering from MITS in Andhra Pradesh, India. Pramod has worked as the owner of RC Educational Foundation Pvt Ltd, a teacher, and an Educational Consultant, and is currently working as an Engineer and Digital Marketer.



Leave a Comment