# Any way to detect division by zero?

In Sage, is there any way (function call) to check whether a given expression will produce division by zero error. Is something like the following possible?

if IsDivisionByZero(expr): return False

In Sage, is there any way (function call) to check whether a given expression will produce division by zero error. Is something like the following possible?

if IsDivisionByZero(expr): return False

4

You can use Python `try...except`

blocks to catch a `ZeroDivisionError`

. For example, I define the two functions

```
def foo(x):
return 1/x
def bar(x):
try:
return 1/x
except ZeroDivisionError:
# error handling: do whatever you want here
print "Returning positive infinity..."
return Infinity
```

This is what the output looks like when giving various inputs into these two functions.

```
sage: foo(1)
1
sage: foo(0)
Traceback (click to the left of this block for traceback)
...
ZeroDivisionError: Rational division by zero
sage: bar(1)
1
sage: bar(0)
Returning positive infinity...
+Infinity
```

You can use `try...except`

blocks outside of function definitions as well.

Asked: **
2010-12-08 12:02:45 -0500
**

Seen: **281 times**

Last updated: **Dec 09 '10**

Replace rows an columns by zeros in a numpy array

accessing data included in the error message

[Solved] Difference about divide operator in python2 and sage

Division of polynomial matrices

dividing vector(a,b) by sqrt(x) gives (a/x*sqrt(x),b/x*sqrt(x))

Copyright Sage, 2010. Some rights reserved under creative commons license. Content on this site is licensed under a Creative Commons Attribution Share Alike 3.0 license.