Chapter-1 Exception Handling in Phython
Chapter-1 Exception Handling in Phython
Sometimes, a single piece of code might be suspected to have more than one type of error.
For handling such situations, we can have multiple except blocks for a single try block.
In the code, two types of exceptions (ZeroDivisionError and ValueError) are handled using
two except blocks for a single try block. When an exception is raised, a search for the
matching except block is made till it is handled. If no match is found, then the program
terminates. However, if an exception is raised for which no handler is created by the
programmer, then such an exception can be handled by adding an except clause without
specifying any exception. This except clause should be added as the last clause of the
try..except block.
try...except…else clause We can put an optional else clause along with the try...except
clause.
But if there is no error then none of the except blocks will be executed. In this case, the
statements inside the else clause will be executed.
FINALLY CLAUSE The try statement in Python can also have an optional finally clause.
The statements inside the finally block are always executed regardless of whether an
exception has occurred in the try block or not. It is a common practice to use finally clause
while working with files to ensure that the file object is closed.
SUMMARY
• Syntax errors or parsing errors are detected when we have not followed the rules of the
particular programming language while writing a program.
• When syntax error is encountered, Python displays the name of the error and a small
description about the error.
• The execution of the program will start only after the syntax error is rectified. • An
exception is a Python object that represents an error.
• The exception needs to be handled by the programmer so that the program does not
terminate abruptly.
• When an exception occurs during execution of a program and there is a built-in exception
defined for that, the error message written in that exception is displayed. The programmer
then has to take appropriate action and handle it.
• Exception Handlers are the codes that are designed to execute when a specific exception is
raised.
• Raising an exception involves interrupting the normal flow of the program execution and
jumping to the exception handler.
• The statements inside the finally block are always executed regardless of whether an
exception occurred in the try block or not.