Exception handling helps a program handle runtime errors gracefully instead of crashing. Debugging helps identify and fix issues efficiently.
Occur due to syntax or logical mistakes.
if True
print("Error") # SyntaxError
Occur during execution.
print(10 / 0) # ZeroDivisionError
| Errors | Exceptions |
|---|---|
| Compile-time / logical | Runtime |
| Program crashes | Can be handled |
| SyntaxError | ZeroDivisionError |
Used to catch and handle exceptions.
try:
risky_code
except ExceptionType:
handling_code
else:
executes_if_no_exception
finally:
always_executes
try:
num = int(input("Enter number: "))
print(10 / num)
except ZeroDivisionError:
print("Cannot divide by zero")
except ValueError:
print("Invalid input")
Runs only when no exception occurs.
try:
print("Hello")
except:
print("Error")
else:
print("No error occurred")
Always executes (used for cleanup).
try:
file = open("data.txt", "r")
except FileNotFoundError:
print("File not found")
finally:
print("Closing resources")
Handling multiple exception types separately or together.
try:
a = int(input("Enter number: "))
b = int(input("Enter number: "))
print(a / b)
except ZeroDivisionError:
print("Division by zero")
except ValueError:
print("Invalid input")
try:
print(int("abc") / 2)
except (ValueError, ZeroDivisionError):
print("Error occurred")
User-defined exceptions are created for business logic validation.
class AgeError(Exception):
pass
def check_age(age):
if age < 18:
raise AgeError("Age must be 18 or above")
print("Access granted")
try:
check_age(16)
except AgeError as e:
print(e)
Logging records program execution details for debugging and monitoring.
DEBUGINFOWARNINGERRORCRITICALimport logging
logging.basicConfig(level=logging.INFO)
logging.info("Program started")
logging.error("An error occurred")
logging.basicConfig(
filename="app.log",
level=logging.DEBUG,
format="%(asctime)s - %(levelname)s - %(message)s"
)
logging.debug("Debugging details")
print("Value of x:", x)
import pdb
pdb.set_trace()
if True
print("Error")
if True:
print("Error")
"10" + 5
int("abc")
print(x)
lst = [1, 2]
print(lst[5])
d = {"a": 1}
print(d["b"])
try:
balance = 5000
amount = int(input("Enter amount: "))
if amount > balance:
raise Exception("Insufficient balance")
print("Withdrawal successful")
except Exception as e:
print("Error:", e)
finally:
print("Thank you for using ATM")