Python Exception Handling (try-except)
Page Info
Content
Python Exception Handling (try-except)
In Python, exceptions are handled using try
, except
, else
, and finally
blocks. This helps catch errors during program execution and prevents abnormal termination.
Basic Exception Handling (try-except)
try:
# Code that may raise an error
result = 10 / 0
except ZeroDivisionError:
# Code to run if ZeroDivisionError occurs
print("Cannot divide by zero!")
Advanced Exception Handling (try-except-else-finally)
try:
# Code that may raise an error
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))
result = num1 / num2
except ZeroDivisionError:
print("Cannot divide by zero.")
except ValueError:
print("Please enter a valid number.")
else:
# Runs if no exception occurs
print(f"Calculation result: {result}")
finally:
# Always runs, regardless of exception
print("Calculation completed.")
Key Points
- Multiple exceptions: Use multiple
except
blocks to handle different types of errors. - Exception info: Use
except Exception as e:
to access error messages or exception details. - Prevent program crash: Try-except blocks ensure that even if an error occurs, the program continues safely.
SEO Keywords
Python try except example, Python exception handling, Python error handling, Python finally block, Python try else finally, Python catch errors
Use exception handling in Python to manage runtime errors, maintain program stability, and provide meaningful error messages to users.
Good0 Bad0
댓글목록
등록된 댓글이 없습니다.