try
, except
, else
, finally
blocksraise
In read-world applications, errors will happen — a user might provide wrong input, a file might be missing, or an API might fail.
Instead of crashing the program, Python provides a graceful way to handle errors using exception handling.
Here are a few examples:
Error | Reason |
---|---|
ZeroDivisionError | Dividing a number by zero |
FileNotFoundError | Trying to open a non-existing file |
TypeError | Wrong data type used in operation |
ValueError | Wrong value passed |
IndexError | Accessing out-of-bound index |
KeyError | Accessing a missing dictionary key |
try:
# risky code
except SomeError:
# handle the error
else:
# runs if no exception
finally:
# always runs
Example: Try and Except
try:
num = int(input("Enter a number: "))
result = 10 / num
print("Result:", result)
except ZeroDivisionError:
print("You cannot divide by zero.")
except ValueError:
print("Please ener a valid number.")
else
and finally
else
runs only if no error occursfinally
always runs (cleanup code, closing files, etc.)
try:
f = open("data.txt", "r')
content = f.read()
except FileNotFoundError:
print("File not found!")
else:
print("File read successfully.")
finally:
f.close()
print("File Closed.")
try:
value = int("abc")
print(10 / 0)
except (ValueError, ZeroDivisionError) as e:
print("Caught an error:", e)
raise
You can raise exceptions if needed:
age = -5
if age < 0:
raise ValueError("Age cannot be negative!")
Create your own exceptions by inheriting from Exception
:
class InvalidAgeError(Exception):
pass
age = int(input("Enter age: "))
if age < 0:
raise InvalidAgeError("Custom: Age can't be negative.")
except:
alone)logging
module)finally
Create a function that:
TypeError
if input is not a listZeroDivisionError
if list is emptyConcept | Keyword | Use Case |
---|---|---|
Handle error | try/except | Gracefully catch runtime errors |
No error block | else | Runs if no exceptions occur |
Always run | finally | Clean-up actions like closing files |
Manual raise | raise | Raise your own exception |
Custom error | class | Create domain-specific error types |
Leave a Reply