Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Python Error Handling with try-except and raise Statements

Tech 1

Using try-except and raise for Input Validation

try:
    gender = input("Enter your gender: ")
    if gender.lower() not in ["male", "female"]:
        raise ValueError("Input must be 'male' or 'female'")
    print("Your gender is:", gender)
except ValueError as e:
    print(e)
except Exception:
    print("An unexpected error occurred")

Example Output:

Enter your gender: other Input must be 'male' or 'female'

or

Enter your gender: female Your gender is: female

Handling Arithmetic Exceptions

try:
    val1 = float(input("Enter first number: "))
    val2 = float(input("Enter second number: "))
    quotient = val1 / val2
    print(quotient)
except ZeroDivisionError:
    print("Cannot divide by zero")
except ValueError:
    print("Invalid numeric input")
except Exception:
    print("An unexpected error occurred")

Example Output:

Enter first number: 10 Enter second number: 0 Cannot divide by zero

or

Enter first number: 10 Enter second number: abc Invalid numeric input

or

Enter first number: 10 Enter second number: 2 5.0

Using else and final Blocks

try:
    x = float(input("Enter numerator: "))
    y = float(input("Enter denominator: "))
    result = x / y
except ZeroDivisionError:
    print("Division by zero error")
except ValueError:
    print("Invalid number format")
except Exception:
    print("General error")
else:
    print("Division result:", result)
finally:
    print("Operation complete")

Example Output:

Enter numerator: 10 Enter denominator: abc Invalid number format Operation complete

or

Enter numerator: 10 Enter denominator: 2 Division result: 5.0 Operation complete

Basic Debugging with Breakpoints

counter = 1
while counter < 5:
    print(counter)
    counter += 1
Tags: Python

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.