How to use try except in python

Python’s exception handling system lets you write code that can deal with unexpected errors

The structure

try:
    # Code that might have problems
except ExceptionType as e:
    # What to do if an error occurs
else:
    # Runs if there's no error
finally:
    # Cleanup code - always runs

Explanation of the structure:

  • try: “This is where we put the code that might cause problems.”
  • except: “If an error happens in the ‘try’ block, the code in ‘except’ tells Python what to do.”
  • else: “This part runs only if there’s no error in the ‘try’ block.”
  • finally: “This code runs no matter what, error or not. It’s great for cleaning up things like closing files.”

The try…except structure in Python aims to prevent programs from crashing by providing a way to handle exceptions. This allows you to continue execution or provide meaningful error messages instead of the program terminating unexpectedly.




import math

def calculate_square_root(num):
	try:
		result = math.sqrt(num)
	except ValueError as ve:
		print(f"Error: {ve}")
	else:
		print(f"The square root of {num} is {result}.")

# Test the function
calculate_square_root(4)    # This will print "The square root of 4 is 2.0"
calculate_square_root(-4)    # This will print "Error: math domain error"




Published by

mashiurrahman99

Programmer