Exception Handling in Python: Calculating Square Roots
Introduction:
Exception handling is essential to manage errors gracefully and ensure programs run smoothly without crashing. In Python, this is achieved using try, except, and raise constructs. This article demonstrates how to handle exceptions in Python by calculating a number's square root, focusing on effectively handling invalid inputs.
Problem Statement
The goal is to create a Python program that calculates the square root of a given number. The program should:
- Accept two inputs: a base number and an exponent (0.5 for square root).
- Calculate the square root of the base number.
- Handle invalid inputs such as negative numbers and non-numeric values.
- Provide clear error messages for user guidance.
Approach:
1. Input Validation: Accept user input as floats to handle both integers and decimal numbers.
2. Exception Handling: Use a try block to perform calculations and an except block to catch ValueError for invalid inputs.
3. Raise Exceptions: Use raise to throw an exception if the base number is negative, as square roots of negative numbers are not real numbers.
4. Error Messaging: Provide meaningful error messages for incorrect inputs.
Get Swati Meher’s stories in your inbox
Join Medium for free to get updates from this writer.
Code Implementation:
Here’s the code:
def generate_square_roots(number1, number2):
try:
if number1 < 0:
raise ValueError
return number1 ** number2
except ValueError as ve:
print("Invalid input! Please enter a positive integer or a float value", ve)
number1 = float(input("Enter the number "))
number2 = float(input("Enter square root of "))
print(generate_square_roots(number1, number2))Demo:
When you execute the program, it will run as follows:
Conclusion:
Exception handling in Python is crucial for building robust applications. By using ‘try’, ‘except’, and ‘raise’, we can handle errors gracefully and provide meaningful feedback to users. This code example demonstrates how to calculate square roots while managing invalid inputs effectively, illustrating best practices for error handling in Python.
Happy Coding ;)











