DEV Community

Shahrouz Nikseresht
Shahrouz Nikseresht

Posted on

Simple Error Handling with try and except Explained Again (Beginner Focus)

Handling errors prevents programs from crashing on unexpected input.

Basic try-except

try:
    number = int(input("Enter a number: "))
    print(10 / number)
except:
    print("Invalid input or zero. Please try again.")
Enter fullscreen mode Exit fullscreen mode

Specific errors

try:
    age = int(input("Enter age: "))
    print(100 / age)
except ValueError:
    print("Please enter a valid number.")
except ZeroDivisionError:
    print("Age cannot be zero.")
Enter fullscreen mode Exit fullscreen mode

With else and finally

try:
    num = int(input("Number: "))
except ValueError:
    print("Not a number.")
else:
    print(f"Success: {num * 2}")
finally:
    print("Done.")
Enter fullscreen mode Exit fullscreen mode

Simple examples

Safe calculator:

try:
    a = float(input("First: "))
    b = float(input("Second: "))
    print(a / b)
except ValueError:
    print("Enter numbers.")
except ZeroDivisionError:
    print("Cannot divide by zero.")
Enter fullscreen mode Exit fullscreen mode

Read number safely:

try:
    value = int("hello")
except ValueError:
    print("Conversion failed.")
Enter fullscreen mode Exit fullscreen mode

Quick summary

  • Put risky code in try.
  • Catch errors in except.
  • Use specific error types.
  • else runs on success, finally always runs.

Practice adding try-except to input code. It makes programs more user-friendly in Python programs.

Top comments (0)