In programming, an exception is an error that occurs during the execution of a program. When an exception occurs, the program stops running and prints an error message. Exception handling is the process of dealing with these errors in a way that doesn't cause the program to crash.
In Python, you can handle exceptions using the try/except block. The code that might raise an exception is placed inside the try block, and the code to handle the exception is placed inside the except block. Here is the basic syntax:
try:
# code that might raise an exception
except ExceptionType:
# code to handle the exception
When an exception occurs in the try block, Python looks for an except block that matches the type of exception raised. If a matching except block is found, the code inside that block is executed. If no matching except block is found, the program will stop running and print an error message.
There are many different types of exceptions that can occur in Python. Here are a few common ones:
Now that you know the basics of Exception Handling, let's move on to some examples.
In this example, we will use a try/except block to handle a ValueError when converting a string to an integer.
# Easy Example
user_input = input("Enter a number: ")
try:
number = int(user_input)
print("The number is:", number)
except ValueError:
print("Invalid input. Please enter a number.")
In this code, the user is asked to enter a number. The input is then converted to an integer using the int() function. If the input is not a valid number, a ValueError will be raised and the code inside the except block will be executed. The output of this code will be:
Enter a number: abc
Invalid input. Please enter a number.