Questions tagged [exceptions]
An exception is an occurrence in an application process that requires deviation from the program's normal flow.
613
questions
1
vote
1
answer
250
views
Is the use of a catch block as a "rollback mechanism" a bad thing?
I have a service that performs a series of actions based on user information (name, address, etc), one of the problems is that the User entity comes from a legacy third party API (as a repository) ...
5
votes
6
answers
412
views
Unsupported concurrent calls, throw exception or log a warning?
Context
Let's say I have a navigation service that allows me to navigate to a page.
The Navigate method is async because an animation (about 250ms) is involved.
public interface INavigator
{
...
14
votes
14
answers
6k
views
Should I raise an exception/error when an optional argument is used but is not necessary?
Take this constructed example:
def fetch_person(person_id, country_code=None):
if is_fully_qualified(person_id):
return person_source_1.fetch_person(person_id)
else:
return ...
0
votes
3
answers
87
views
Communicating error conditions in client API for remote RESTful server, what's the best way?
I'm writing an application based on a RESTful API located in a server (written in Python).
An Android app will access the API endpoints to get, post, put or delete data. The usual.
The server has a ...
2
votes
3
answers
175
views
Handling exogenous exceptions in layered architecture
Exogenous exceptions are that kind of exception that are unavoidable because they are throwed outside of our system's pristine logic.
A good practice is to throw wrapped exceptions in lower layers ...
2
votes
2
answers
138
views
Is nesting try-except sequence in try-else block bad form?
Ive got a boot sequence that needs to check some registry values, they may or may not be present, so each check needs to be wrapped in its own try-except. I try to avoid nesting as I think it can lead ...
2
votes
1
answer
137
views
How do we maintain consistent-read promise to clients + handling ID collision when using a fallback queue?
In my company, we are using Event Sourcing pattern to implement a storage for all changes to the price of a booking. Across the company, different services might try to append events to a booking ...
8
votes
10
answers
595
views
Boneheaded exceptions should not be caught. Then how to provide fault tolerance and reliability?
I've always been taught that fatal exceptions (indicating problems that cannot be solved programmaticaly) and boneheaded exceptions (resulting from bugs in my code) should not be caught, should not be ...
2
votes
2
answers
428
views
Is returning true or throwing an exception good or bad code practice?
I am focosing on learning better design and wondered if this code is good or an antipattern? The function validate return true if data is correct, else it will throw an exception with a message to ...
2
votes
3
answers
626
views
Business logic error handling. Should exceptions really be avoided?
C#'s primary error handling mechanism are exceptions and try pattern.
We don't have access to discriminated unions yet like in case of F# and Rust Option<T> and Result<T, E> types.
The ...
27
votes
14
answers
8k
views
What's the logic behind the design of exceptions?
I'm writing an application in C#. I'm facing an InvalidConstraintException, but from that Exception, I seem not to be able to access the Constraint, causing the Exception. That specific question is ...
0
votes
2
answers
152
views
How can I avoid re-running code when exceptions are thrown and user re-submits?
I have a checkout process that 1) creates a user account in Stripe and my database, 2) creates a paymentMethod in Stripe and logs the last4 in the database, 3) creates the subscription in Stripe and ...
0
votes
2
answers
201
views
Is it bad to use checked exceptions as API response?
Consider the following code:
public class User {
private String password;
public void changePassword( String oldPassword,
String newPassword) throws ...
6
votes
3
answers
352
views
How to simplify exception handling for library users?
Suppose of having a library exposing the following piece of functionality:
public static class AwesomeHelpers
{
public static async Task<int> ComputeSomethingImportAsync(CalculationInputs ...
0
votes
1
answer
79
views
Exception handling with failure atomicity in desktop applications
When it comes to exception handling, there are many guidelines and best practices on the web. On of them is to throw early, catch late, or even Don't Catch. So when facing an exception, the current ...
2
votes
2
answers
455
views
Validations and throwing exceptions in DDD?
I have a question regarding validations and exceptions in DDD.
I have a ValueObject say, PasswordText which takes a string argument in it's constructor. Checks if the string matches the password ...
3
votes
3
answers
1k
views
Should try-catch blocks be used when calling functions that already have them?
In JavaScript, if I have try catch blocks in a function that is meant to be called from another function, should I also put them in the calling function or just let the called functions handle them.
...
1
vote
2
answers
112
views
Best Practice: Unit test coverage vs. in-method sanity checks [duplicate]
I have a code-coverage requirement of of a certain percentage, and face the following tradeoff:
Should I sacrifice in-method sanity checks and error handling for ease of (unit-) testability?
Lets ...
1
vote
2
answers
154
views
Catch "foreign" exception in adapter and convert them in own business exception is a good practice?
I am currently thinking about some design choices regarding exception handling.
My current architecture looks a little like this:
You can see that I have a UI where a try-catch middleware is cathing ...
1
vote
2
answers
86
views
Are the exceptions used in BeanValidation/JAX-RS's ExceptionMapper an anti pattern?
I am reading a lot about patterns and code structure and something that bothers me is BeanValidation's way to handle errors. I like Java and think that BeanValidation is easy to use, but it seems to ...
-2
votes
4
answers
112
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 ...
0
votes
3
answers
199
views
Confusion about basic exception handling and rethrowing exception [duplicate]
I came across this question and super confused about rethrowing concept in the following example:
try
{
// code that may throw exceptions
}
catch(Exception ex)
{
// add error logging ...
-2
votes
2
answers
261
views
Where to place exception handling while using Decorator design pattern
How to design a service layer structure that will be resistant to exceptions. Let's say I have a simple OrderService service, this service performs basic operations - saving an order.
public interface ...
1
vote
1
answer
33
views
Failed uploads layer
I am trying to find an optimal way to handle the following scenario:
I have an application where there are a lot of file uploads on a certain endpoint, but the validation is rather strict as per the ...
6
votes
1
answer
459
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 ...
0
votes
3
answers
226
views
What is the proper way to throwing an exception?
I'm currently make a Helper class that can be used by multiple team members. Helper class uses third party API. And I have a question about that handles exceptions in the Helper class.
https://docs....
2
votes
4
answers
280
views
Is it common practice to declare exceptions in a library that won't be thrown or caught anywhere within that library?
I have a very basic library that serves the purpose of collecting some useful but simple pieces of code. Like for example a Percent struct or functions like ToDegrees() and ToRadians(), just to give ...
31
votes
10
answers
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:
...
1
vote
4
answers
168
views
Displaying exceptions
I read/watch about Uncle Bob's clean code and when he talks about exceptions he suggested to have a well named exception over a description which make perfect sense for the programmer, for decoupling ...
60
votes
9
answers
7k
views
Why do "checked exceptions", i.e., "value-or-error return values", work well in Rust and Go but not in Java?
Java has "checked exceptions", which force the caller of the method to either handle an exception or to rethrow it, e.g.
// requires ParseException to be handled or rethrown
int i = ...
7
votes
3
answers
322
views
How to deal with abandoned idempotent operations?
I have implemented idempotent order placement (mostly to avoid accidental double submissions) but I am not sure how to handle incomplete operations. Example scenario:
User tries to place an order.
An ...
5
votes
1
answer
154
views
Clean way to handle different exceptions in Javascript?
I'm Java developer and I'm now learning Javascript creating a personal project.
I don't know how to handle different errors in Javascript in a clean way and I can't find a good solution on the web.
I'...
2
votes
2
answers
168
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
2
answers
746
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
...
2
votes
1
answer
134
views
Exception handling with adapter design pattern in JavaScript
I am using an opencv.js Web Assembly build in the browser. The build comes with a JavaScript interface to call the WASM functions but it does not provide any memory management. For example every time ...
1
vote
1
answer
89
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 ...
0
votes
1
answer
303
views
Mark exception as handled, rethrow, display
Inside my business logic, I have something like a pipeline with multiple actions. Each action wrapped into try/catch and can handle exceptions by himself (logging, saving state for retry ex). And I ...
-1
votes
1
answer
71
views
Should wrong command call throw an exception?
If I expect specific arguments for a command call, and its called wrongly by the user, should the program throw an exception?
In python I would like to write something like:
assert 'author' in args, '...
4
votes
1
answer
235
views
Catching base exception to throw a more specific exception?
I have an Accessor and Repository interface. Accessor abstracts over where to store JSON documents (local file system, NoSQL database, etc). Repository abstracts over the representation of my domain ...
-1
votes
5
answers
581
views
How to manage exceptions in a long call stack
When throw a exception inside java method, IntelliJ suggest to add exception to method signature. When I have a long call-stack as below how I manage these exceptions.
method 1() -> method 2() ->...
0
votes
3
answers
2k
views
Is throwing custom exceptions from private methods OK?
(I moved this question here, as StackExchange fits better, originally I posted it on StackOverflow.)
This is not a question about a particular piece of code, rather I ask what is the right design ...
0
votes
1
answer
65
views
Exception handling for a page with multiple sections
Context:
We have a page which is composed of multiple sections.
Consider for e.g: A product page with Product details, prices, images & offers.
All the sections are shown one after the other in ...
1
vote
5
answers
625
views
Is this an anti pattern or misusing the interface default method?
Instead of checking the null and throwing exception each time we call findByOrderNumber method, I came up with this pattern by taking advantage of a default method, are there any patterns misused here ...
1
vote
1
answer
97
views
What is better way to track mistakes in error-prone part of a feature?
That is quite specific circumstances I've come across, and I somewhat struggle to find proper way how to approach this.
I'm given a class written in swift-language, which has a control property, like ...
0
votes
2
answers
376
views
Is it good practice to throw exceptions in parsing functions
I basically read across the entire internet that exceptions are bad, slow and should be avoided whenever possible. This confuses me because I thought I have a "valid" case to use exceptions.
Consider ...
3
votes
3
answers
207
views
Should you define an equality test solely for testing?
Assume you have a class C. C defines a public method (member function) C::m1.
Calling c.m1() (c is an instance of C) can either
Return after mutating the object c it was called on.
Throw an ...
4
votes
4
answers
5k
views
Throwing exception from constructor?
I have this NamePath class that accepts a string from some system path and tries to split it into two properties, Name and LastName.
Is the code example below fine? I've read that throwing exceptions ...
1
vote
2
answers
180
views
Is logging every exception with FirstChanceException event handler a bad practice?
I joined a company and the project I'm working on have an event handler that extends the FirstChanceException functionality to log the exceptions. The logs are stored in a file and not registered to ...
1
vote
1
answer
107
views
Where to handle duplicate key exceptions in multy layer application
+-------------+ +--------+ +----------+
| repository +-------->+service +------->+controller|
+-------------+ +-^------+ +------------+
+-------------+ | ...
-1
votes
2
answers
61
views
Execute sequence of methods conditionally and log possible error
I'm not sure if this is the adequate site (maybe CodeReview?) but it's the only one here in StackExchange that have got a "clean code" tag ... There is no need for downvotes if this is not the correct ...