Exception Handling

Person coding at a desk with laptop and external monitor showing programming code.

Exception handling in Python allows a programmer to handle runtime errors by catching exceptions and taking appropriate action to handle them. In Python, exceptions are raised when an error occurs during execution of the program. An exception can be handled using a try statement, which allows the programmer to catch exceptions and take appropriate action.
The general syntax for an exception-handling block is:

try:
   # code that may raise an exception
except ExceptionType:
   # code that handles the exception

The ExceptionType in the except statement is the type of the exception to be handled. For example, if you are trying to divide a number by 0, a ZeroDivisionError exception will be raised. To handle this exception, you can use the following code:

The finally clause can also be used to specify a block of code that will always be executed, whether an exception is raised or not. The syntax for the finally clause is:

try:
   # code that may raise an exception
except ExceptionType:
   # code that handles the exception
finally:
   # code that will always be executed

In this way, exceptions can be handled effectively in Python and prevent the program from crashing.

Types of Errors in Python

There are two main types of errors in Python:
Syntax Errors: Occur when the Python interpreter encounters an error in the syntax of the code. It is usually a typo or a violation of the rules of the programming language.

Exceptions: Occur when the code encounters a problem during execution. They are runtime errors and are usually caused by incorrect input or unexpected data. Examples of exceptions include ZeroDivisionError, IndexError, and TypeError.

Exception Handling using try The “try” statement in Python allows you to handle exceptions by executing a block of code that is susceptible to an exception. The syntax for the try statement is as follows:

try:
   # code that may raise an exception
except ExceptionType:
   # code to handle the exception

Here, the code inside the “try” block is executed. If an exception is raised, the control of the program goes to the “except” block, where you can handle the exception. The “ExceptionType” in the “except” clause can be any of the built-in exceptions in Python.

try:
  num1 = int(input(“Enter a number: “))
  num2 = int(input(“Enter another number: “))
  result = num1 / num2
  print(result)
except ZeroDivisionError:
  print("Division by zero is not allowed")

In this example, the try block takes two inputs as numbers and performs division. If the second number is zero, a ZeroDivisionError exception is raised, and the code in the except block is executed to handle the exception.

Exception Handling using except
Exception Handling using except The except keyword is used to handle exceptions raised by the try block in Python.
The syntax is:

try:
    # code block to be executed
except ExceptionType as e:
    # code block to handle the exception

where ExceptionType is the type of exception raised, and e is an optional variable that stores the error message associated with the exception. The except block contains the code to handle the exception, such as printing an error message, retrying the operation, or performing a different action.
Here’s an example:

In this example, the try block tries to divide 10 by 0, which raises a ZeroDivisionError. The except block catches this error and prints an error message to the console.

Exception Handling using finally
The finally statement in Python can be used along with try and except to handle exceptions. The code in the finally block is always executed, regardless of whether an exception is raised or not. The purpose of using finally is to clean up resources (such as closing a file or releasing a
lock) regardless of whether an exception occurs or not.
For example:

try:
# code that might raise an exception
  a = int(input("Enter a number:"))
  print(10/a)
except ValueError:
  print("Invalid input, must be a number")
finally:
  print("This will always be executed")

In this example, the user is prompted to enter a number. If the user enters an invalid input, a ValueError is raised and the code in the except block is executed. Regardless of whether an exception was raised or not, the code in the finally block is executed to clean up resources.

To buy Python books click the below links
Python Programming
Python Programming 2E
Handbook of Python Programming

Leave a Comment

Your email address will not be published. Required fields are marked *