---
title: "How to handle exceptions in Python using try-except blocks?"  
description: "How to handle exceptions in Python using try-except blocks?"  
author: "Steilla Mitchel"  
published: 2023-07-04  
updated: 2023-07-05  
canonical: https://www.mindstick.com/forum/158956/how-to-handle-exceptions-in-python-using-try-except-blocks  
category: "python"  
tags: ["exception handling", "python"]  
reading_time: 2 minutes  

---

# How to handle exceptions in Python using try-except blocks?

How to [handle exceptions](https://www.mindstick.com/forum/159234/how-do-you-handle-exceptions-using-the-try-catch-block-in-java) in [Python](https://www.mindstick.com/articles/75378/simple-yet-useful-tips-when-using-python) using try-[except](https://www.mindstick.com/blog/144/union-intersection-and-except-operator-in-sql-server) blocks?

## Replies

### Reply by Aryan Kumar

Sure, I can help you with that.

**How to [handle](https://www.mindstick.com/articles/311004/suede-skillet-handle-cover) [exceptions](https://www.mindstick.com/interview/22871/define-predifined-generic-exceptions) in Python using try except blocks**

In Python, exceptions are events that occur during the execution of a program that disrupt the normal flow of the program. Exceptions can be caused by a variety of things, such as invalid input, trying to divide by zero, or accessing a nonexistent object.

To handle exceptions in Python, you can use try except blocks. A try except block is a block of code that is executed as a "normal" part of the program. However, if an exception occurs during the execution of the try block, the except block is executed instead.

The syntax for a try except block is as follows:

Python

```plaintext
try:
  # This is the code that is executed as a "normal" part of the program.
except Exception as e:
  # This code is executed if an exception occurs.
  # The variable `e` contains the exception object.
```

Here is an example of a try except block:

Python

```plaintext
try:
  number = int(input("Enter a number: "))
  result = 10 / number
except ValueError:
  print("You did not enter a valid number.")
except ZeroDivisionError:
  print("You cannot divide by zero.")
else:
  print("The result is", result)
```

This code will first ask the user to enter a number. If the user enters a valid number, the result of the division will be printed. However, if the user enters an invalid number or tries to divide by zero, an exception will be raised and the appropriate except block will be executed.

The `else` block in a try except block is executed if no exception occurs. This is useful for code that you want to execute only if the try block executes without any errors.


---

Original Source: https://www.mindstick.com/forum/158956/how-to-handle-exceptions-in-python-using-try-except-blocks

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
