#๐ exception handling
17 messages ยท Page 1 of 1 (latest)
@native musk
Remember to:
- Ask your Python question, not if you can ask or if there's an expert who can help.
- Show a code sample as text (rather than a screenshot) and the error message, if you've got one.
- Explain what you expect to happen and what actually happens.
:warning: Do not pip install anything that isn't related to your question, especially if asked to over DMs.
Have you got a specific question, or some example?
It's not complex, but hard to succinctly describe.
not really it may be about anything in the exam so what I'm facing is i dont understand it that much
Ok.
Python "raises" an exception when something goes wrong. This might be a call which failed like open("nonexistent-filename") or an invalid value for a function call like int("not an integer!").
This has 2 main features:
- you can, loosely, write code as if it will work and rely on it raising an exception for bad situations - this avoids a lot of if-statements like
if "abc".find("def") == -1: # "def" wasn't there- statements whose purpose os to "check" for failure - you can decide where to handle to problem - sometimes (often!) it's not something to fix where it happened because the "fix" depends on some larger context
A try/except statement is for catching raised exceptions:
try:
with open("nonexistent-filename") as f:
... process the data in the file ...
except FileNotFoundException:
# handle the file not being there
data = [] # no data, but ok!
Generally:
- you want the try/except around the smallest piece of code possible, so that you know what raised the exception
- you want to catch only things for which you have a well defined recovery action - in the above, we consider a missing file to be ok, we will pretend like it was empty
- you don't catch other things, so that they can bubble out and be debugged
That last is: suppose we got an exception because we do not have read permission on the file. We do not catch that because that isn't something we should paper over and ignore. Probably it means we're trying to work on data we shoud not have access to or the outer environment is badly set up. Either way, we don't catch it.
That's most of it. There's a heap of details, but that's the core stuff.
Questions?
Glad to be of service.
This help channel has been closed. Feel free to create a new post in #1035199133436354600. To maximize your chances of getting a response, check out this guide on asking good questions.