Read the Python traceback from the bottom before you touch try/except: the last line names the real error, and everything above it is only the call path. This piece covers how Chennai and Tamil Nadu engineers should catch FileNotFoundError or ValueError, never a bare except, when else and finally run, and why logging beats print — so you recover what a user can survive and let genuine bugs crash.
- Read a traceback from the bottom. The last line is the real error. The lines above it are only the path that got you there.
- Handle only what you can recover from. A missing file? Yes. A bug in your own math? No. Let that crash on your laptop.
- Never write a bare except. Catch ValueError, FileNotFoundError, or a class you named.
- else runs when nothing failed. finally runs even if something did. Do not guess which one you need.
- print() dies with the terminal you closed. logging is what an on-call person still has at 2am.
What is Python error handling, in one line?
It is you deciding what happens when a line cannot finish its job.
Search python try except and half the answers dump a copy-paste blanket around the whole file. That is not handling. Handling is reading the crash, naming the exception, and writing a path a user can survive — a retry, a clear message, or a clean stop.
Python raises an Exception object when something is wrong. You catch it, or the program dies and prints a traceback. Both outcomes are valid. The skill is knowing which one you want.
How do you read a traceback from the bottom?
Your intern in a Chennai bay just hit Enter. The terminal went red. Do not scroll to the top. Do not Google the first word you see. Look at the last line.
That last line is the exception type and the message. FileNotFoundError: No such file or directory: 'orders.csv'. That is the whole story in one sentence.
Now walk up. Each File ..., line ... block is a function that called the next one. The lowest block that sits in your project — not inside site-packages — is the line you mistyped or mis-fed.
If the crash is inside a library you did not write, you still caused it. You passed a bad path, a None, an empty string. The library is not haunted. Your argument is.
Read it twice before you type try. Half the error handling juniors write is just hiding a typo they could have fixed in thirty seconds.
How do try, except, else and finally actually work?
try is the risky bit. except is the recovery. else is the nothing-went-wrong lane. finally is the cleanup that runs no matter what — success, failure, even a return inside try.
Think of a UPI debit. You attempt the pay. Wrong PIN? Tell the user. It works? Show the success tick. The socket still needs closing either way. That last part is finally.
from pathlib import Path
def read_config(path: str) -> str:
file = None
try:
file = open(path, encoding="utf-8")
data = file.read()
except FileNotFoundError:
print("Config file is missing.")
return ""
except PermissionError:
print("No permission to read that file.")
return ""
else:
return data.strip()
finally:
if file is not None:
file.close()
sample = Path("demo_config.txt")
sample.write_text("theme=dark\n", encoding="utf-8")
print(read_config("demo_config.txt"))
print(read_config("no_such_file.txt"))In day-to-day code you will often write with open(...) as file, which does the close for you. Learn finally anyway. Interviews in Bengaluru, Hyderabad and Pune still ask what runs if the except block also raises.
Answer: finally still runs. Then the new exception leaves the function. That one fact clears a surprising number of written tests.
else is underrated. Put the happy work there when you want to be sure no exception happened. Mixing success logic inside try makes you catch errors you never meant to catch.
Why should you catch specific exceptions, never a bare except?
except: with nothing after it catches KeyboardInterrupt too. You hit Ctrl+C. The program swallows it. You cannot stop the script. That is not clever. That is a trap.
except Exception: is only a little better. It still hides bugs — AttributeError because you typed .nam instead of .name, TypeError because you added a str to an int. Those should crash on your laptop, not vanish on a client's server at 11pm.
def parse_amount(text: str) -> int:
try:
return int(text.strip())
except ValueError:
print("That is not a number. Try again.")
return 0
print(parse_amount("499"))
print(parse_amount("na"))You wanted a number. ValueError is what int() raises on na. Catch that. If someone passes None, let TypeError explode. You will find the caller in five minutes instead of three days.
You can stack except blocks, most specific first. You can write except (ValueError, TypeError) when the recovery is truly the same. If the recovery is different, use two blocks. Do not invent a common handler just to save four lines.
When do you write your own exception classes?
When the failure is a business rule, not a Python rule.
int("abc") is a ValueError. A wallet that cannot pay Rs 800 because it has Rs 200 is not a ValueError. It is your domain. Give it a name the next developer can grep at 2am.
class InsufficientBalanceError(Exception):
def __init__(self, needed: int, available: int) -> None:
self.needed = needed
self.available = available
super().__init__(
f"Need Rs {needed}, wallet has Rs {available}"
)
def pay_upi(amount: int, wallet: int) -> int:
if amount < 1:
raise ValueError("amount must be at least 1")
if amount > wallet:
raise InsufficientBalanceError(amount, wallet)
return wallet - amount
print(pay_upi(100, 500))Subclass Exception, not BaseException. BaseException is for SystemExit and KeyboardInterrupt. You do not want a payment failure to look like a shutdown.
Keep the class small. Store the numbers you will need in an except block. Put a clear message in super().__init__. A 200-line script does not need a 12-level exception tree. One or two named classes beat a string you parse later.
Why log errors instead of using print?
print goes to the terminal you closed. logging goes to a file, to stdout that systemd keeps, or to the cloud log your on-call actually opens.
When a booking-style job fails at 2am, nobody is watching the console. If you printed, they see nothing. If you logged with logger.exception, they see the message plus the traceback.
import logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
def fetch_order(order_id: str) -> dict[str, str]:
try:
if not order_id:
raise ValueError("order_id is empty")
return {"id": order_id, "status": "packed"}
except ValueError:
logger.exception("Bad order id: %s", order_id)
raise
print(fetch_order("A102"))logger.exception belongs inside an except block — it attaches the current traceback. logger.error("msg") does not. Use %s placeholders, not an f-string in the call, so the logger can skip the work when that level is off.
Do not log and swallow unless you have a real fallback. Log, then raise, is the pattern that keeps dashboards honest. A silent except is how a wrong INR total leaves the building.
Which mistakes get people into trouble?
Bare except, we already covered. These still fail code review.
Catching and returning None with no log. The caller then does order["status"] and you get a TypeError twenty frames later. You did not handle the error. You moved it.
except Exception as e: pass. The pass is the crime. If you must ignore something rare, name the type and write a comment a senior will believe.
Using exceptions for the normal path — raising EndOfList instead of ending a for loop. Exceptions are for the unusual case. They make the happy path ugly, and they cost more than an if.
Catching in the wrong layer. A web handler that catches a database error and returns ok will ship bad data. Let it fail, or map it to a 500 with a log line. Indian SaaS teams would rather see one failed request than a quiet wrong total.
What should you do now?
Service companies in Chennai, Pune and Hyderabad still put traceback reading on the first Python round. They paste a stack, ask which line is yours, then ask you to rewrite a bare except. Product teams that look like Flipkart checkout or GPay webhooks want custom exceptions for stock, balance, duplicate order — not a generic Exception dumped in a util.py.
Open an old script tonight. Find every except:. If it has no type, add one. If it prints, switch to logging. If it returns None, decide whether raising is kinder.
Practice task: write load_rates(path) that reads integer rupee amounts, one per line. Catch FileNotFoundError and PermissionError separately. On ValueError for a bad line, log it and skip. Raise a custom EmptyRatesError if nothing valid remains. Close the file with finally or a with block. Run it on a missing file, an empty file, and a file with 100, abc, 250.
You will feel slow the first time. After that, a red terminal is just a map.



Comments (0)
Be the first to comment!