bytes
tutorials
python
exception handling
Overview
Exceptions are mistakes discovered during execution. Exceptions are triggered whenever there is a mistake in a program. The program will come to a standstill if these exceptions are not handled. Python exception handling is essential to prevent the program from ending unexpectedly. This post will go over Exception Handling in Python in further detail.
What is Exception Handling in Python?
Exception handling in Python is a process of resolving errors that occur in a program. This involves catching exceptions, understanding what caused them, and then responding accordingly. Exceptions are errors that occur at runtime when the program is being executed. They are usually caused by invalid user input or code that is invalid in Python. Exception handling allows the program to continue to execute even if an error occurs.
Syntax:
try:
# code that may cause an exception
except ExceptionType as e:
# code to handle the exception
else:
# code to execute if no exceptions were raised
finally:
# code that will always be executed, regardless of exceptions
This is an example of the syntax for handling exceptions in Python. A try block contains code that can throw an exception ⚠️. If an exception occurs, the code in the except block is executed, which helps to handle the Exception. The else block is optional and is only executed if no exceptions occur. Finally, the code inside the finally block will always be executed regardless of any exceptions💯 .
Common Exceptions in Python
Try Except in Python
Python provides a way to catch specific exceptions during a program's execution. This is done with the "try" statement. The basic syntax looks like this:
try:
# code that may cause an exception
except ExceptionName:
# code that will be executed if an exception occurs
For example, if we wanted to catch a ZeroDivisionError, we could do something like this:
try:
x = 5 / 0
except ZeroDivisionError:
print("You can't divide by zero!")
This code will print "You can't divide by zero!" if a ZeroDivisionError is encountered during execution.
Raising Custom Exceptions in python
You can create custom exceptions in Python by creating a new exception class. To create a custom exception, you must define a new class inherited from the Exception class. You can add custom attributes, methods, and other logic to your custom exceptions as needed. Example:
class CustomError(Exception):
"""Custom Exception class"""
def __init__(self, message):
self.message = message
super().__init__(message)
try:
raise CustomError("This is a custom exception")
except CustomError as e:
print(e.message)
This code creates a custom exception class called CustomError. This exception class inherits from the base Exception class and has a custom message attribute. When the Exception is raised, the message is passed to the init method and set as the message attribute. In the except block, the message attribute is printed.
Try except and ELSE!
Try and Except in Python is a way of handling errors and exceptions in Python. It is used to catch any errors that may occur during the execution of a program and provide a graceful way to handle them. The syntax for using try and except is as follows:
try:
# code that may throw an exception
except ExceptionType:
# code to handle the exception
else:
# code that will only execute if no exception was raised
The code inside the try block is executed until an exception is raised. If an exception is raised, the code inside the except block is executed. The code inside the else block is executed if no exception is raised.
Try Clause with Finally
try:
x = 5
y = 0
z = x/y
except ZeroDivisionError:
print("Error: Cannot divide by zero")
finally:
print("All done")
This code divides the variable x (set to 5) by the variable y (set to 0). Since this is impossible (dividing by 0), the code will throw a ZeroDivisionError. The except statement catches this error and prints a message to the user. The finally statement will run regardless of whether or not an error occurs, and in this case, it prints "All done".
Why Use Finally or Else in try..except?
Finally and Else are two keywords used in try..except blocks in Python. The Finally block executes a set of statements, regardless of the result of the try..except blocks. This is useful when you want to clean up resources like closing a file or connection, irrespective of whether an exception occurred or not. The Else block is used to execute a set of statements only if the try block does not raise an exception. It is useful for code that must be executed if the try block does not raise an exception.
What Happens if Errors are Raised in Except or Finally Block?
If an error is raised in an except or finally block, the error will be handled by the next outer try-except statement, or if there is no outer try-except statement, the error will be raised to the caller.
try:
x = 1/0
except ZeroDivisionError:
print("Division by zero not allowed")
finally:
try:
print(y)
except NameError:
print("Variable y is not defined")
# Output: Variable y is not defined
This code is trying to divide 1 by 0, which will raise a ZeroDivisionError. This error is handled by the except block, which prints out "Division by zero not allowed". Then, the finally block tries to print the variable y, which is not defined. This raises a NameError, which is handled by the inner try-except statement in the finally block, which prints out "Variable y is not defined".
Conclusion
We learned about Exception Handling in Python, including how to raise and catch exceptions, use try-except blocks, create custom exceptions, and use the finally clause. We can now use our newfound knowledge to handle errors and exceptions in her Python code, enabling us to write more robust and reliable programs.
Key takeaways
📝
Quiz
Answer: a. raise Exception
Answer:a. except Exception
Answer:c. After the try statement is executed
Answer:a. To execute code if an exception is not thrown