All Questions
Tagged with python exceptions
34
questions
-2
votes
4answers
103 views
Is this a good approach to stop an API function and return relevant error message?
I am writing an API function using DRF where I want the API execution to stop if it fails in any of the steps and return an appropriate response. So I created a custom exception which takes an error ...
6
votes
1answer
172 views
Handling same exception thrown by different methods
Is there an idiomatic way to catch an exception when multiple methods may throw?:
try:
someMethod() # raises OSError
someOtherMethod() # raises OSError
except OSError:
handle()
The ...
30
votes
10answers
7k views
What is a good approach to handling exceptions?
I have trouble reconciling "best practices" and real-world approaches to handling exceptions. In my day to day routine, I find myself running into the following examples:
try:
...
2
votes
2answers
139 views
Code repeated in multiple exception blocks
I'm starting to notice this pattern throughout some of my code:
try:
some_func()
except FirstException as err: # known possible err
# log err
notify_user(err)
except SecondException as ...
1
vote
2answers
328 views
Is using nested try-except blocks problematic?
I've been seeing a lot of this construct throughout my application:
def doSomething():
try:
# setup some variables
try:
# do something that could throw an OSError
...
1
vote
1answer
85 views
Should exception-blocks handle only exceptions raised from try-blocks?
Should the exception blocks in a try-except sequence be specific only to those exceptions which may originate from the try? Or can they be inclusive of exceptions that may arise from handling the ...
2
votes
2answers
768 views
What is the difference between unit testing and handling exceptions
I have spent two full days now trying to understand the difference between unit testing and handling exception, but I can't get it.
Things I have understood (or I think I have):
Unit testing tests ...
1
vote
2answers
901 views
Exceptions versus guard clauses
I'm trying to get my head around Python exceptions. I've read quite a bit on the topic but can't get clear answers to some questions. In particular, I'm still not sure whether to use exceptions or ...
1
vote
1answer
478 views
Best practices for handling application specific exceptions?
Is it considered to be a good practice to convert all types of exceptions (exceptions from internal logic of application + exceptions from application's external dependencies - for example: File ...
1
vote
1answer
150 views
Is raising an unrelated exception for convenience acceptable? [duplicate]
Let's say I have a function that returns a dataset. First it tries to read it and if that fails it is requested from an API and then written:
def get_dataset():
try:
df = pd.read_csv('...
-1
votes
3answers
471 views
Reasoning behind custom class Exception
I am learning Python and when I learned that we can build Custom classes for exception, I got into a confusion of Why ?
for example1 :
class MyException(Exception):
def __init__(self, error):
...
4
votes
2answers
246 views
Design of multi-test function to validate a string
Assume that I wish to perform an action on a string (e.g., print the string) if, and only if, the string first passes several tests. The tests are diverse (and may even be complex functions themselves)...
24
votes
3answers
12k views
Are exceptions for flow control best practice in Python?
I'm reading "Learning Python" and have come across the following:
User-defined exceptions can also signal nonerror conditions. For
instance, a search routine can be coded to raise an exception ...
1
vote
5answers
3k views
Is it better to have many specified exceptions or some general that are raised with specified description?
What is the better way to organize exception in a Python project? What is the right way to use exception description?
For example I have a function that parse email and return some data from it's ...
3
votes
4answers
1k views
Why raise an exception if python raises it for me?
I have a global position keeper of screen items so items don't need store their own positions.
class Screen_Position_Keeper:
# functions to add stuff
def get_px_row( self, item ):
...
3
votes
1answer
3k views
What is considered best practice for custom exception classes?
Python has many strong conventions but I'm unclear on how best to manage exceptions for my module. I know it's generally good practice to define a custom exception for your module. E.g.:
class ...
1
vote
1answer
148 views
Does exception handling belong at the lowest level of the runtime?
I'm designing a fairly simplistic stack-based programming language, and implementing it in Python. (no link, because it's not fully implemented yet.)
The language itself is essentially intended to be ...
6
votes
4answers
3k views
Handling exceptions I don't know about
When I work with handling exceptions, I notice that I often have to deal with the ones I had no idea about. Especially it is noticeable when I program a method that grabs data from web. An error may ...
1
vote
2answers
26k views
How can you catch all index out of range errors in python?
Our program does these kinds of operations hundreds of times for many different variables and lists, then uses them throughout the program:
variable = values[5]
The list values are coming from the ...
4
votes
4answers
3k views
Should exceptions be raised higher up or lower down or both? [closed]
When calling some function in a Python application, the function often calls functions deeper down which again call functions deeper down, etc. It is easy to unknowlingly pass a bad value to the top-...
6
votes
2answers
16k views
Exception handling in Python - Am I doing this wrong (and why?)
I've read many questions and articles on exception handling in Python (and in general), but I still think that it's the most confusing thing ever. I ended up doing something like this:
# error class ...
1
vote
2answers
172 views
How do I find out what type of exception I am supposed to raise?
I suppose this question is valid for any programming language that can handle (or at least throw) an exception. However I will stick to Python as an example.
The top 2 answers to the following ...
10
votes
1answer
2k views
When should I subclass an exception in Python?
In my code there are about seven places where I raise an exception. All of these exceptions are treated the same: print an error to log file, return software state to default and exit.
During code ...
5
votes
1answer
295 views
Should I use exceptions to control the range of parameters in Python?
For example for the following method signature:
def genClusters(n_clusters, n_nodes, cluster_distribution):
n_clusters should be an integer of more than 1.
n_nodes should be an integer of more ...
13
votes
2answers
18k views
Is it safe to catch ImportError when trying to import optional modules?
I usually see this pattern at least once in every Python project I work on. For example, in a Django project, this is often added at the bottom of the base settings file:
try:
from .local_settings ...
10
votes
4answers
29k views
How to clean up nested try/except/else?
When writing code, I often want to do something like this:
try:
foo()
except FooError:
handle_foo()
else:
try:
bar()
except BarError:
handle_bar()
else:
...
37
votes
3answers
26k views
Is it conventional to raise a NotImplementedError for methods whose implementation is pending, but not planned to be abstract?
I like to raise a NotImplementedError for any method that I want to implement, but where I haven't gotten around to doing it yet. I might already have a partial implementation, but prepend it with ...
3
votes
2answers
1k views
Inform caller or just let them deal with exception?
I'm not sure how to proceed in the following situation.
say we have a function as so:
def runsATask(codes):
myDicts = [helperFunc(code) for code in codes]
for item in myDicts:
# some ...
23
votes
4answers
16k views
When and how should I use exceptions?
The Setting
I often have trouble determining when and how to use exceptions. Let's consider a simple example: suppose I am scraping a webpage, say "http://www.abevigoda.com/", to determine if Abe ...
46
votes
4answers
8k views
Python Forgiveness vs. Permission and Duck Typing
In Python, I often hear that it is better to "beg forgiveness" (exception catching) instead of "ask permission" (type/condition checking). In regards to enforcing duck typing in Python, is this
try:
...
99
votes
9answers
26k views
Check First vs Exception Handling?
I'm working through the book "Head First Python" (it's my language to learn this year) and I got to a section where they argue about two code techniques:
Checking First vs Exception handling.
Here is ...
51
votes
4answers
41k views
Why do iterators in Python raise an exception?
Here's the syntax for iterators in Java (somewhat similar syntax in C#):
Iterator it = sequence.iterator();
while (it.hasNext()) {
System.out.println(it.next());
}
Which makes sense. Here's the ...