Python Try Block

Advertisements
Advertisements

The python try block is part of python exception handling mechanism. The try block is similar to an if-then-else block. If an error occurs the try block stops executing. These errors are known errors for which we have a try block. They are called exceptions.

The try block is to notice the error or exception that happened and stop executing.

After that you can have a catch block in python that will handle the error in most appropriate way. Usually the error handling routine is written by the programmers.

Syntax Try Block

There may be code outside the try block and any error in those parts will not be catched. The syntax for try block is given below.

# The try block
number_d = 10
number_s = int(input("Enter a number :"))
try:
    result = number_d/number_s
    print(result)
except:
    pass

In the example above, the variables – number_d and number_s are declared outside of the try block, therefore, no error will be caught.

Advertisements

If the value of number_s is 0, there will be a ZeroDivisionError and the program will exit without printing anything because the except keyword does not do anything and let the block pass.

Therefore, output of the above program will be empty. See the figure below.

try-except block
try-except block

Instead of pass, you can print a customized error to indicate what error was caught. Note that we already know that a ZeroDivisionError would happen.

Consider the modified program from above.

# The try block
number_d = 10
number_s = int(input("Enter a number :"))
try:
    result = number_d/number_s
    print(result)
except:
    print("Cannot divide by Zero. Try different integer")

The output of the above program is following when number_s is 0.

Enter a number :0
Cannot divide by Zero. Try different integer
>>> 

In the next article, we will understand more about exception handling, especially, the catch block(except).


Bestseller

Python Programming: Using Problem Solving Approach

Python Programming is designed as a textbook to fulfil the requirements of the first-level course in Python programming. It is suited for undergraduate degree students of computer science engineering, information technology as well as computer applications. This book will enable students to apply the Python programming concepts in solving real-world problems. The book begins with an introduction to computers, problem solving approaches, programming languages, object oriented programming and Python programming. Separate chapters dealing with the important constructs of Python language such as control statements, functions, strings, files, data structures, classes and objects, inheritance, operator overloading and exceptions are provided in the book. Each chapter ends with objective-type questions, review questions, programming and debugging exercises to facilitate revision and practice of concepts learnt.


Advertisements
Advertisements
Advertisements