Exception Handling In Python

Exceptions : An exception can be defined as an event, which generally occurs during the runtime of the program execution. When Exception occurs in runtime, the program will get terminated abruptly. We will not have any understanding why the program got terminated.

If an exception occurs in program, we need to handle it during the runtime or else our program will get terminated.

How to Handle an Exception?
We can handle the exception by placing our code within try: block which should be followed by the except : statement.

Python Exception Handling Syntax :

try:

a set of statements

except Exception:

If exception occurs execute these statements

Problem Statement : Below is the example, which has no syntactical error. When the program is executed, the error will occur during runtime.

Output :

Python_Without_Exception_Handling

Here when we execute the program, the program will get terminated abruptly without giving the exact reason. Since the above program has few lines of code we can identify the issue quickly. Where as if we have more than 100 lines of code we need to spend a lot of time to identify the issue.

Hence Python language came up with an mechanism to handle the exceptions.

After applying Exception handling mechanism :

Output :


Python_With_Exception_Handling_Example

How try except block work?
1.In the above program if no error occurs, except block will not be executed.
2.In the above program if error occurs, then except block will be executed.

Try-finally Clause :

There is a situation where we need to execute a particular set of statements mandatorily, even though exception occurs or not. Then we need to place our code within finally block.

Python Try-finally Clause Syntax :

try:

set of statements

finally:

Always this code executes

Python try-finally clause Example :

OUTPUT :

Python_Finally_Example

Raising Exceptions in Python :

Exceptions that occur in Python are raised during runtime. If we want to raise an exception forcefully, then we can raise it through keyword raise.

Example :

OUTPUT :

Leave a Comment

Your email address will not be published.