The python except block is the catch block in the exception handling mechanism. Any error or exception caught in the try block is caught by the python except block and response code is executed.
In the previous article, you learned about the try block and in the article, we will explore the except block in details.
Catching Different Types of Exceptions
A program can generate many errors and a single except always is not the right choice. You may catch a
Name error in your program, but you may not be able to identify and catch a
Value error in your program.
Therefore, you need
- multiple except blocks or catch blocks
- each must catch a specific error and respond to it
Naming An Except Block
You can name an except block and it will catch only those errors that it meant to be and respond appropriately.
Consider the following example.
try: x = 10 y = 23 z = y/0 # zero division error print("Successful",c) # variable C does not exist, it's a name error except ZeroDivisionError: print("Unable to divide by zero!")
In the example above, there is a
z = y/0. The except block is only looking for ZeroDivisionError. It will ignore any other exception or error.
try block may contain many errors, but as soon as an exception is met the try block stop the execution of codes and look for a except block(catch block).
Look at the
print statement in the try block, it is trying to print a non-existing variable
C. This will cause a
Name Error, however, that does not happen because the try block already found the
ZeroDivisionError. No further execution take place.
Here is the output of the above program.
== RESTART: C:/Python_projects/Exception Handling/named_exception.py == Variable does not exist >>>
Let us modify the above program and add multiple exceptions.
Multiple Exception Handling in Python
Once we add multiple except blocks, each with its own name, we can catch and respond to many errors in the try block.
Here is the modified example from above.
try: x = 20 y = 40 z = y/x print("Successful",C) # variable C not exist except ZeroDivisionError: print("Unable to divide by zero!") except NameError: print("Variable does not exist!!")
Now, the ZeroDivisionError is fixed and the program is trying to print non-existent variable C. This will result in a
Name Error. Since, that is the only error we encounter, the except block (catch block) will respond immediately.
== RESTART: C:/Python_projects/Exception Handling/named_exception.py == Variable does not exist!! >>>
Multiple Error Handling In the Same Except Block
You can also catch more than one error using same except block. You may have to identify the correct response based on the error. Consider the following example.
try: x = 10 y = 23 z = y/x print("Successful",C) except (ZeroDivisionError , NameError): print("Unable to divide by zero! or a Name Error occurred")
The except block will catch any of the two errors –
a ZeroDivisionError or
a Name Error. However, the response is common to both the errors.
Multiple Exception Handling in Using Different Except Blocks
You do not need to keep all the exceptions grouped like in the above example. You may keep them separate and for each of these exception write a different response. This is certainly an improvement compared to grouping multiple exceptions in the same except block.
See the example below.
try: x = 10 y = 23 z = y/x print("Successful",C) except NameError: print("Name Error occurred") except TypeError: print("Type error occurred")
Each type of exception has its own response code.
Storing Exception in a Variable
Python programming allows you to catch an exception and store it in another variable. The you can print the value of that variable or manipulate it.
Here is an example,
try: x = 10 y = 23 z = y/"Hello" print("Successful",x) except TypeError as err: print(err)
In the code above, the error is stored in the variable called
err.Later, we printed the error using that variable. Here is the output to the program above.
unsupported operand type(s) for /: 'int' and 'str' >>>
The error clearly states that it is a Type Error.
All the above errors are known error types. What if we want to catch unknown exception because in many programming languages ,
unknown exceptions happen all the time.
Handling Unknown Exceptions in Python
In python, you can handle all the unknown exceptions using a single except block called
Exception.Let us see an example.
try: x = 10 y = 23 z = y/0 print("Successful",x) except TypeError as err: print(err) except Exception: print("Unknown error occurred!")
The program above catch
Type Error and if an error type is not type error, then the
Exception block will catch it and print “Unknown error”.
Note that an
exception block is catch unknown exceptions that may or may not happen. For all other types you must write your own error handling codes.
In the next article, we will discuss about the Else block and its role in exception handling.
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.