Introduction
Try-except-else helps you handle errors in your code safely. It lets you run special code if no errors happen.
Jump into concepts and practice - no test required
Try-except-else helps you handle errors in your code safely. It lets you run special code if no errors happen.
try: # code that might cause an error except SomeError: # code to handle the error else: # code to run if no error happened
The else block runs only if the try block did not raise any error.
If an error happens, the else block is skipped.
else block prints the result.try: x = 10 / 2 except ZeroDivisionError: print("Cannot divide by zero") else: print("Division successful, result is", x)
except block runs, and the else block is skipped.try: x = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero") else: print("Division successful, result is", x)
This program defines a function to divide two numbers. It uses try-except-else to handle division errors. If division works, it prints the result. If division by zero happens, it prints an error message.
def divide_numbers(a, b): try: result = a / b except ZeroDivisionError: print("Error: Cannot divide by zero.") else: print(f"Division successful: {a} / {b} = {result}") print("Test 1:") divide_numbers(10, 2) print("Test 2:") divide_numbers(10, 0)
The else block is useful to keep the code that runs only when no errors happen separate and clear.
Use except to catch specific errors you expect, so you don't hide other bugs.
try runs code that might fail.
except runs if an error happens.
else runs only if no error happened.
else block do in a try-except-else structure?try block runs code that might cause an error. If an error happens, the except block runs.else block runs only if no error occurs in the try block, meaning the code succeeded without exceptions.try, then except, then else. The else block must come after except.try:
print("Start")
x = 1 / 1
except ZeroDivisionError:
print("Error")
else:
print("No Error")
print("End")except block is skipped, else block runs printing "No Error", then "End" prints after.try:
print(10 / 0)
else:
print("No error")
except ZeroDivisionError:
print("Error occurred")def check_value(val):
try:
result = 10 / val
except ZeroDivisionError:
return "Cannot divide by zero"
else:
return f"Result is {result}"
print(check_value(0))
print(check_value(5))
What is the output?