Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to handle the ArithmeticError exception in Python

Onyejiaku Theophilus Chidalu

Overview

ArithmeticError is simply an error that occurs during numeric calculations.

ArithmeticError types in Python include:

  • OverFlowError
  • ZeroDivisionError
  • FloatingPointError

These errors are all capable of crashing a code in Python. It is essential to catch an error because you do not want your code to crash as a result of incorrect input from you or a user.

How to identify an ArithmeticError

The program below will reveal what error will arise from our code.

arithmetic = 5/0
print(arithmetic)

You can see that the code above returns an error output that reads as follows:

ZeroDivisionError: division by zero

This is a type of ArithmeticError.

Mathematically, dividing an integer by zero is wrong, and that is the reason why Python crashes the program and returns an error message.

How to handle an ArithmeticError

Now, let us see how we can catch any of these errors in our code.

try:
  arithmetic = 5/0
  print(arithmetic)
except ArithmeticError:
  print('You have just made an Arithmetic error')

Explanation

  • Line 1: We introduce the try, except block to help us check for errors in our line of codes.
  • Line 2: We create a variable, arithmetic.
  • Line 3: We return the output of our variable.
  • Line 4: We use except to check for an ArithmeticError and complete the block.
  • Line 5: If there is an ArithmeticError in our code, we have previously told Python to return a text output instead of crashing our program.

RELATED TAGS

python
communitycreator

CONTRIBUTOR

Onyejiaku Theophilus Chidalu
RELATED COURSES

View all Courses

Keep Exploring