0% found this document useful (0 votes)
5 views

Python_try_except_tutorial_cleaned

This document provides a tutorial on exception handling in Python, explaining the use of try, except, else, and finally blocks. It includes examples demonstrating basic syntax and various scenarios of handling exceptions. The summary table outlines the purpose of each keyword used in exception handling.

Uploaded by

jiya23022009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Python_try_except_tutorial_cleaned

This document provides a tutorial on exception handling in Python, explaining the use of try, except, else, and finally blocks. It includes examples demonstrating basic syntax and various scenarios of handling exceptions. The summary table outlines the purpose of each keyword used in exception handling.

Uploaded by

jiya23022009
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 3

Python try-except-else-finally Tutorial

What is Exception Handling in Python?


Exception handling lets you handle runtime errors using:
- try: Code that might raise an error.
- except: Code to handle the error.
- else: Code that runs if no error occurs.
- finally: Code that always runs.

Basic Syntax
try:
# Code that may raise an exception
except ExceptionType:
# Handle exception
else:
# Runs if no exception occurs
finally:
# Always runs

Example 1: Basic try-except


try:
x = 10 / 0
except ZeroDivisionError:
print("You can't divide by zero!")

Example 2: try-except-else
try:
x = 10 / 2
except ZeroDivisionError:
print("Division by zero error")
else:
print("Division successful:", x)
Example 3: try-except-finally
try:
x = int("123")
except ValueError:
print("Invalid input!")
finally:
print("This always runs.")

Example 4: All combined


try:
number = int(input("Enter a number: "))
result = 10 / number
except ZeroDivisionError:
print("Can't divide by zero.")
except ValueError:
print("Invalid input.")
else:
print("Success! Result is:", result)
finally:
print("Execution complete.")

Example 5: Multiple Exceptions


try:
x = int("abc")
y = 10 / 0
except ValueError:
print("Value error occurred.")
except ZeroDivisionError:
print("Zero division error occurred.")

Example 6: Catch All Exceptions


try:
x=1/0
except Exception as e:
print("An error occurred:", e)

Summary
| Keyword | Purpose |
|-----------|----------------------------------------------|
| try | Wrap code that might throw an exception |
| except | Handle specific exceptions |
| else | Run if no exceptions occurred |
| finally | Always runs (useful for cleanup actions) |

You might also like