Raising Exceptions In Subroutines


When writing Python in Sage, we can anticipate certain errors and attempt to intercept them. This is called raising an exception, and is performed with the raise command. We will write a simple subroutine that divides two numbers that, and will raise an exception if the user attempts to divide by zero. The kind of exception we raise here is called a RuntimeError. In other words, this tells the system that an error was encountered while the subroutine was being executed.

Sage Cell


def divideUs(a, b):
    if (b == 0):
        raise RuntimeError("Cannot divide by zero! Please use another value for b.")

    return a/b

divideUs(2, 0)


Exception Types

A RuntimeError is essentially a "catch-all" exception type for something that doesn't fit into Python's other exception categories. If we wanted to be as accurate as possible, we would raise a ZeroDivisionError:

A full list of exception types for Python 2.7 can be found here.

def divideUs(a, b):
    if (b == 0):
        raise ZeroDivisionError("Cannot divide by zero! Please use another value for b.")

    return a/b

divideUs(2, 0)


Primary Tags:

Secondary Tags:

A list of possible tags can be found at The WeBWorK Open Problem Library. For linear algebra tags see the Curated Courses Project.

Related Cells

Any related cells go here. Provide a link to the page containing the information about the cell.




Date: 14 Mar 2019 16:47

Submitted by: Zane Corbiere

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License