Exception is an event that arises when an error occurs during the execution of a program. Python uses exception objects to represent these exceptions, signaling that something has gone awry. Here’s a simple example illustrating how to raise and handle an exception
In Python, when an error occurs during the execution of a program, an exception is raised. These exceptions can be caught and handled using the try/except
block. Let’s break down how this works.
Common Examples of Exception:
Division by Zero
Accessing a file that does not exist.
Addition of two incompatible types
Trying to access a nonexistent index of a sequence
Removing the table from the disconnected database server.
ATM withdrawal of more than the available amount
Python Exception Handling Mechanism
Exception handling in python is managed by the following 3 keywords:
try
catch
finally
Throw or raise
try and except Statement
The most simple way of handling exceptions in Python is by using the try
and except
block.
Run the code under the
try
statement.When an exception is raised, execute the code under the
except
statement.
Instead of stopping at error or exception, our code will move on to alternative solutions.
The try
Block
The try
block is where we put the code that might cause exceptions. When Python sees a try
block, it tries to run the code inside it. If an exception happens during this run, the control is passed to the corresponding except
block.
The except
Block
The except
block is where we define what to do when exceptions happen. It acts as a backup plan, allowing the program to handle errors without stopping abruptly. By naming the exception type to catch, we can customize our response to different situations.
Example Program 1
try:
a=int(input("Enter number 1: "))
b=int(input("Enter number 2: "))
print(a+b)
except Exception:
print("Error")
Output:
Enter number 1: 5
Enter number 2: gokul
Error
Example Program 2
try:
a=int(input("Enter number 1: "))
b=int(input("Enter number 2: "))
print(a-b)
except ValueError as e:
print("Value Error",e)
except TypeError as e:
print("Type error", e)
Output:
Enter number 1: 5
Enter number 2: gokul
Value Error invalid literal for int() with base 10: 'gokul'
The catch Statement
The sort of exception that it is likely to catch is one that is taken one argument at a time by catch blocks. These justifications might be anything from a particular sort of exception that can be changed to a general category of exceptions.
Norms for the catch block:
You can define a catch block by using the keyword catch
The catch Exception parameter is always enclosed in parentheses
It always represents the type of exception that the catch block handles.
An exception handling code is written between two {} curly braces.
You can place multiple catch block within a single try block.
You can use a catch block only after the try block.
All the catch block should be ordered from subclass to superclass exception.
Finally Statement in Python
Whether or not there is an exception, the finally block always runs. You may write a block of code that comes after a try-catch block by using the final keyword.
A clause is optional, to sum up. It aims to provide cleanup procedures that must be followed in all circumstances.
Example Program 3
try:
a=int(input("Enter number 1: "))
b=int(input("Enter number 2: "))
print(a-b)
except ValueError as e:
print("Value Error",e)
except TypeError as e:
print("Type error", e)
finally:
print("Done")
Output:
Enter number 1: 25
Enter number 2: hi
Value Error invalid literal for int() with base 10: 'hi'
Done
Congrats🎉, On Learning the Exception handling in python with example programs.
Happy Learning :)