You are currently viewing Error handling: Try & Except
Python | Error handling

Error handling: Try & Except

In Python, error handling is done using the try and except statements. These statements are used to catch and handle exceptions that occur during program execution. The try the statement contains the code that might raise an exception, while the except statement handles the exception that is raised.

Here’s an example:

try:
    x = int(input("Please enter a number: "))
    print("The number you entered is:", x)
except ValueError:
    print("Invalid input! Please enter a valid number.")

In this example, the try block contains the code that asks the user to enter a number. If the user enters something other than a number, a ValueError will be raised. The except block catches this exception and prints an error message.

You can also catch multiple exceptions by using multiple except blocks:

try:
    x = int(input("Please enter a number: "))
    print("The number you entered is:", x)
except ValueError:
    print("Invalid input! Please enter a valid number.")
except:
    print("An error occurred!")

In this example, the second except block catches any exception that is not a ValueError.

You can also use the finally block to specify code that should be executed no matter what:

try:
    x = int(input("Please enter a number: "))
    print("The number you entered is:", x)
except ValueError:
    print("Invalid input! Please enter a valid number.")
finally:
    print("Thank you for using our program.")

In this example, the finally block contains code that will always be executed, whether or not an exception was raised.

You can also raise exceptions yourself using the raise statement:

x = input("Please enter your name: ")
if not x.isalpha():
    raise ValueError("Invalid name! Please enter a valid name.")
print("Hello,", x)

In this example, if the user enters something that contains non-alphabetic characters, a ValueError will be raised.

Overall, error handling is an important part of writing robust and reliable Python programs. By using try and except statements, you can catch and handle exceptions gracefully, making your code more robust and easier to maintain.

Leave a Reply