Show code
try:
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError:
print("Cannot divide by zero.")Gujuri Alekha
Oct 20, 2024
Try-Except Block: In Python, you can use a try block to enclose the code that might raise an exception. If an exception occurs within the try block, the program immediately jumps to the corresponding except block.
Finally Block: You can also include a finally block after the try and except blocks. Code inside the finally block will always run, whether an exception occurred or not. It’s typically used for cleanup operations like closing files or network connections.
Exception class or one of its subclasses. Here’s how you can raise a custom exception:BaseException. This class is the parent of all built-in exceptions. More specific exceptions inherit from higher-level exceptions, which allows you to catch exceptions at different levels of granularity.ArithmeticError is a subclass of BaseException and is the parent class of exceptions like ZeroDivisionError.ZeroDivisionError is a subclass of ArithmeticError.Get new notebooks as they're published
New parts are added to each track in order. Follow along:
@online{alekha2024,
author = {Alekha, Gujuri},
title = {Python {Exceptions:} Try, Except and Finally},
date = {2024-10-20},
url = {https://gujurialekha.github.io/blog/python/06-python-error-handling-and-exceptions.html},
langid = {en}
}