Table of Contents

Handling Runtime Errors in Python | Pictoblox

Example Description
Learn how to handle runtime errors in Python with an example code. Understand how to avoid runtime errors caused by strings or zero inputs.

Introduction:

In this tutorial, we will discuss an example of handling runtime errors in Python. Specifically, we will look into how to handle errors caused by user inputs of strings or zero values. We will provide a code snippet that demonstrates the issue and discuss ways to avoid such runtime errors.

Code:

#Runtime Errors Example
num1 = 10.0
num2 = int(input("num2 = "))
#if user inputs a string or a zero, it leads to runtime error
print(num1/num2)

Logic:

  1. The code snippet in this example takes a user input, which is assigned to the variable num2.
  2. The code then tries to divide num1 by num2 and prints the result.
  3. However, if the user inputs a string or a zero, it would lead to a runtime error.
  4. This code is used to demonstrate how to handle such runtime errors.

Output:

The output of this code snippet will vary depending on the user input. If the user inputs a valid non-zero number, the program will divide num1 by num2 and print the result. If the user inputs a zero or a string, a runtime error will occur.

 

 

if user inputs a string, say apple

ValueError: invalid literal for int() with base 10: ‘apple’

 

if user inputs a zero

ZeroDivisionError: float division by zero

 

if user inputs a float, say 3.0

ValueError: invalid literal for int() with base 10: ‘3.0’

 

if user inputs an int, say 3

3.3333333333333335