Python Basics with Try and Except rule
“Python Basics with Try and Except rule
In Python, try and except statements are used for error handling. These statements allow you to write code that anticipates and handles potential errors that might occur during runtime.
Here is a basic example of using try and except:
try:
# code that might raise an error
x = 5 / 0
except:
# code that handles the error
print("An error occurred")
In this example, the code inside the try block attempts to divide 5 by 0, which is not allowed and would normally raise a ZeroDivisionError. However, because the code is wrapped in a try statement, the interpreter will not stop the program, but instead will execute the except block.
The except block simply prints out a message to indicate that an error occurred. You can customize the message to provide more specific information about the error, like this:
try:
# code that might raise an error
x = 5 / 0
except ZeroDivisionError:
# code that handles the error
print("You cannot divide by zero")
In this updated example, the except block is looking specifically for a ZeroDivisionError and will only execute if that particular error occurs. The message that is printed out is also more specific, indicating that dividing by zero is not allowed.
You can also use try and except statements to catch multiple types of errors, like this:
try:
# code that might raise an error
x = int("hello")
except (ValueError, TypeError):
# code that handles the error
print("Invalid input")
In this example, the except block will execute if either a ValueError or a TypeError occurs. The code inside the try block attempts to convert the string "hello" into an integer, which is not possible and would raise a ValueError. It is also possible that a TypeError might occur if the input was not a string at all. In either case, the message printed out by the except block is "Invalid input".
“Python Basics with Try and Except rule
Job Oriented CIU Certifications
CIU Certified
CIU Certified
CIU Certified
** Network Pentester
** Web Pentester
** Linux Security Professional