---
title: "How to test for exceptions using if-statements in python?"  
description: "How to test for exceptions using if-statements in python?"  
author: "Revati S Misra"  
published: 2023-07-20  
updated: 2023-07-20  
canonical: https://www.mindstick.com/forum/159170/how-to-test-for-exceptions-using-if-statements-in-python  
category: "python"  
tags: ["exception handling", "exception", "python"]  
reading_time: 2 minutes  

---

# How to test for exceptions using if-statements in python?

How do I [test](https://yourviews.mindstick.com/story/1427/explosive-facts-about-trinity-test-world-s-first-nuclear-bomb) for [exceptions](https://www.mindstick.com/interview/22871/define-predifined-generic-exceptions) in if-statements in [python](https://www.mindstick.com/articles/75378/simple-yet-useful-tips-when-using-python)?

## Replies

### Reply by Aryan Kumar

You cannot test for exceptions using if statements in Python. You can only catch exceptions using try/except blocks.

The `try`/`except` block is a control flow statement that allows you to execute a block of code and handle any exceptions that are raised. The `try` block is followed by an `except` block, which is where you handle the exceptions.

Here is an example of how to use the `try`/`except` block to test for an exception:

```plaintext
def divide_numbers(x, y):
  try:
    result = x / y
  except ZeroDivisionError:
    print("Error: Can't divide by zero")

result = divide_numbers(10, 0)
```

In this example, the `divide_numbers()` function takes two numbers as input and divides them. If the denominator is zero, the `ZeroDivisionError` exception is raised. The `try`/`except` block catches the exception and prints a message to the user.

The `try`/`except` block can also be used to handle multiple exceptions. For example, the following code shows how to handle both the `ZeroDivisionError` and `ValueError` exceptions:

Python

```plaintext
def divide_numbers(x, y):
  try:
    result = x / y
  except ZeroDivisionError:
    print("Error: Can't divide by zero")
  except ValueError:
    print("Error: Invalid input")

result = divide_numbers(10, 0)
```

In this example, the `divide_numbers()` function takes two numbers as input and divides them. If the denominator is zero, the `ZeroDivisionError` exception is raised. If the input is not a number, the `ValueError` exception is raised. The `try`/`except` block catches both exceptions and prints a message to the user.


---

Original Source: https://www.mindstick.com/forum/159170/how-to-test-for-exceptions-using-if-statements-in-python

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
