Thanks to visit codestin.com
Credit goes to www.tutorialspoint.com

How to catch FloatingPointError Exception in Python?



Catching FloatingPointError Exception in Python

FloatingPointError in Python is an exception that occurs when there is an error in floating-point calculations.

By default, Python does not raise this error for basic operations like dividing by zero; instead, it returns inf or nan. To catch this error, you need to enable it explicitly using the numpy module.

In this article, you will learn how to catch a FloatingPointError by enabling it through NumPy settings and handling it using a try-except block.

When Does FloatingPointError Occur?

FloatingPointError can occur in cases like -

  • Divide by zero in floating-point calculations (if enabled)
  • Overflow in a floating-point operation
  • Invalid operations resulting in nan values

Enabling FloatingPointError in NumPy

To raise FloatingPointError, first of all, we need to enable it in the NumPy seterr() method.

Example: Enabling FloatingPointError

In the following example, using NumPy, we are enabling the FloatingPointError, and performing a division operation with 0.0 as the denominator. Here, we are using the try-except blocks to catch the raised exception.

import numpy as np

# Enable FloatingPointError for division and invalid operations
np.seterr(all='raise')

try:
   a = np.array([1.0])
   b = np.array([0.0])
   result = a / b
except FloatingPointError as e:
   print("Floating point error caught:", e)

Following is the output obtained -

Floating point error caught: divide by zero encountered in divide

Example: Catching Overflow Error

If we try to calculate the exponential value (ex) of a number greater than 709.78, a FloatingPointError is raised, as float in numpy can store values up to 1.7928227943945155e+308. 

In this example, we raise an overflow error and catch it using the FloatingPointError-

import numpy as np

np.seterr(over='raise')

try:
   result = np.exp(1000)
except FloatingPointError as e:
   print("Overflow error caught:", e)

We get the output as shown below -

Overflow error caught: overflow encountered in exp

Example: Handling Invalid Floating Operation

Here, we are trying to calculate the square root of a negative number, which is an invalid operation.

import numpy as np

np.seterr(invalid='raise')

try:
   result = np.sqrt(-1)
except FloatingPointError as e:
   print("Invalid floating operation caught:", e)

The error obtained is as shown below -

Invalid floating operation caught: invalid value encountered in sqrt
Updated on: 2025-06-07T20:25:51+05:30

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements