Stack Exchange Network

Stack Exchange network consists of 175 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange

Questions tagged [exceptions]

An exception is an occurrence in an application process that requires deviation from the program's normal flow.

1
vote
2answers
85 views

Should exceptions be only thrown if I intend to crash the program?

...I wanted to find the source before writing this Q, sadly I couldn't. My mental model was that exceptions were thought as an alternative to returning error codes from a function, which is the C ...
-2
votes
4answers
148 views

Handling an exception thrown in a catch block [closed]

If I'm writing a method, in C# for example, I will use a try catch block. Let's say the method adds some numbers but I log exceptions in the catch block. What's the best way to handle an exception ...
39
votes
4answers
7k views

Exception propagation: When should I catch exceptions?

MethodA calls an MethodB which in turn calls MethodC. There is NO exception handling in MethodB or MethodC. But there is exception handling in MethodA. In MethodC an exception occurs. Now, that ...
1
vote
2answers
100 views

Should you “rebrand” the exception of the library you're using?

Say your making a library Foo that depends on a 3rd-party library Bar. Bar throws a custom exception \OtherVendor\Bar\CustomException. Is it recommended to just throw that exact exception to your ...
0
votes
1answer
100 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 ...
0
votes
0answers
72 views

How to handle error responses in a chain of CompletableFutures?

I have a long chain of completable futures in my project, with each step calling a backend API, which can give multiple error responses and one success response. Now, after parsing the response, I ...
64
votes
12answers
10k views

Having a flag to indicate if we should throw errors

I recently started working at a place with some much older developers (around 50+ years old). They have worked on critical applications dealing with aviation where the system could not go down. As a ...
0
votes
2answers
141 views

Should I track my handled exceptions?

Various analytics tools will track the number of handled and unhandled exceptions (crashes) that happen in an app. This obviously helps us find problems we didn't know existed and will fix it. Quite ...
4
votes
3answers
189 views

Is using exceptions to validate parameters a violation of using exceptions for control flow?

I was reading on SO and SESE about exceptions and control flow, but I can't seem to determine or figure out if using exceptions to validate parameters is a violation of that guideline. Suppose I had ...
1
vote
3answers
329 views

How to deal with an unknown situation in a system?

When a caller makes a call to a callee, exception's are used to inform the caller that something different has happened so that he could change the flow of the program if required. In that sense, ...
5
votes
6answers
478 views

Why is it bad to use exceptions for handling this type of validation? It seems like it makes the code so much cleaner

I'm working on a .NET Core REST API and I'm writing a service class to create new user accounts. I have the following code: public async Task<UserDto> RegisterNewUserAccount(...
1
vote
3answers
317 views

Is avoiding throwing an exceptions OK?

e.g I'm parsing whole Excel file with many rows, that has an column which contains Date. I'm not sure how to handle error-handling when it comes to parsing string to DateTime Here's an sample code ...
2
votes
4answers
228 views

Check if resource exists before inserting to the database or wait until the DAO throw the Exception?

I have two paths: /students /students/{id}/addresses ...with the following behavior: POST to /students - 201 Created (if successfully created the Student) POST to /students/{id}/addresses - 201 ...
0
votes
7answers
444 views

Is it a good practice to use self-defined exception?

Our team has different opinions about the practice of using self-defined exception for handling the business logic. Someone says it is good as the exception comes meaningful and readable, and the ...
0
votes
1answer
39 views

Reuse JSE checked exceptions as unchecked

Actually what i'm doing in my code base is duplicating already existing java checked exceptions like MalformedURLException.class by keeping the same exception name while inheriting from ...
0
votes
2answers
230 views

Is it beneficial to throw a caught IOException as an UncheckedIOException in order to prevent NullPointerException?

Not using UncheckedIOException, NullPointerException possible public void callerMethod() { Object result = ioMethod(); // call instance method of result } public Object ioMethod() { ...
1
vote
2answers
152 views

Is passing an ErrorMessage to be populated inside the receiving method an anti-pattern?

I come from a Java background, and my colleague is from .NET. We are working on a Java project and I saw him create a method like this: public Object myMethod(Object[] param1, ErrorMessage ...
4
votes
2answers
194 views

Verifying Parameters in Constructor or Service

I was reading on this SO page about when to check parameters when constructing an object. The accepted answer suggests throwing the exception from the constructor so that an invalid object cannot be ...
1
vote
5answers
659 views

Limits of Defensive Programming acknowledging that Exception Handling should be avoided

I've read Defensive Programming vs Exception Handling? and if/else statements or exceptions, but none contain something relevant to what I'm searching for. Taking into account that exception handling ...
0
votes
3answers
187 views

Too much logic in a nested catch block

My lead dev complained that I have too much logic in a nested catch block. My code goes something like this: try { // some setup and a network call } catch (CustomEx ex) { try { ...
0
votes
1answer
120 views

Simple but frequently throwing vs reasonable but rarely throwing vs complex but never throwing [duplicate]

A lot of code that's designed to convert or parse some data of type Foo into a Bar is written with the assumption that one wouldn't intentionally pass it invalid inputs. As such, it assumes that ...
3
votes
4answers
137 views

Passing a callback all the way down or throw an Exception?

I have a service, call it Service A, that is built on a Storage Layer, call it DB, that is 5-6 levels deep. This layer is depended upon by many other services. Service A is having memory issues and ...
8
votes
6answers
1k views

Should reused exceptions types be favored over single use ones?

Let's say I have Doors that are managed by a DoorService. The DoorService is in charge of opening, closing and locking the doors that are stored on the database. public interface DoorService { ...
3
votes
2answers
2k views

How to deal with exceptions in DLLs?

I recently started working on an existing project written in C++ Builder. The application consists of a MainModule that loads lots of modules (DLLs). The MainModule itself is a DLL (there is a small ...
5
votes
3answers
835 views

Should I localize exception messages?

It is probably related to "Who should read Exception.Message if at all" and similar questions asked on this site, but I don't see how it is possible to always generate a custom message while avoiding ...
0
votes
1answer
799 views

Catching exceptions in service layer without hiding bugs

Let's imagine we have a service CustomerService: public class CustomerService { public Customer GetCustomer(string customerName) { if(string.IsNullOrWhiteSpace(customerName)) ...
1
vote
1answer
221 views

Is it wrong to prefer exceptions to centralize error handling logic?

Using C++, often I hear that you should avoid throwing exceptions for flow control and you should avoid calling functions in conditions where you know they will throw. For example, if a function ...
77
votes
10answers
13k views

Exceptions, error codes and discriminated unions

I've recently started a C# programming job, but I've got quite a bit of background in Haskell. But I understand C# is an object-orientated language, I don't want to force a round peg into a square ...
-1
votes
1answer
230 views

Best practice for handling many exceptions

I have Java microservice that exposes multiple APIs. Under each API there are many exceptions could be thrown. The last method that catches them all has big catch block ... catch(exc1 e1 | exc2 e2 | ...
12
votes
5answers
4k views

Should service throw exception or return when no items specified for deletion

I have a piece of code that can be represented as: public class ItemService { public void DeleteItems(IEnumerable<Item> items) { // Save us from possible NullReferenceException ...
2
votes
1answer
197 views

What exception to throw when the XML is not correctly structured?

What kind of exception should I throw if the XML can be parsed, but is not structured in the way expected by the program - wrong tag names etc. Example - Expected <xml> <tag1>blabla</...
9
votes
2answers
345 views

Granularity of Exceptions

I've run into a debate between a few friends and I. They prefer general exceptions such as ClientErrorException and ServerErrorException with detail as fields of the exception, whereas I prefer making ...
4
votes
2answers
915 views

Should a Connect() Method return false on failure or throw exception?

I found this question Return magic value, throw exception or return false on failure?, however it is kind of broad. I would like a more specific answer. Say I have a method called Connect() which ...
0
votes
2answers
52 views

Throwing custom exceptions in library: do I throw concrete ones or their superclass?

I am designing a library that abstracts a typical CRUD http service named FooService. In this library I am throwing different exceptions like FooServiceClientException for network related errors or ...
1
vote
2answers
1k views

Web API : Centralize business transaction logic : Good Idea?

We develop on a ASP.NET Web API where we use the "Unit Of Work / Repository" pattern : Our Controllers looks like that : public class MyController : Controller { private IUnitOfWork _unitOfWork; ...
0
votes
2answers
121 views

How should I handling throwing exceptions in C#? [duplicate]

I'm developing a game engine in C# and I just had a question about handling exceptions correctly. Since the engine will be used by other .NET developers, how should I handle exceptions? What I mean ...
3
votes
2answers
200 views

Ruby: Exceptions for flow control inside an .each block

Consider the following minimal example: class SomeException < StandardError end class Example @@logger = Logger.new @@failure_count = 0 def do_a_thing(array) raise SomeException unless ...
6
votes
2answers
5k views

Best practice for exception handling in Java threads

long-time reader, first-time asker here. I have a service which writes data to a database in batches. It contains a buffer which is being watched by a separate thread. Whenever the buffer reaches a ...
1
vote
1answer
176 views

Best way to manage services and exceptions

I have a mobile app who consumes a api service. I have a class to manage all the operations (get, post, put) who throws exceptions if the result is not 200. The app was originaly designed to be ...
0
votes
1answer
91 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('...
2
votes
1answer
83 views

How to handle a hierarchy of exceptions - by wrapping or by inheritance?

I'm writing a reusable library, and I'm looking for a way to handle the exceptions that might occur during the processing. For example, I have the following class: public interface IObjectFetcher { ...
6
votes
2answers
6k views

Mapping exceptions to error response

Imagine a program which exposes a REST service/gRPC service/whatever service, which uses several 3rd party libraries. These libraries can of course throw exceptions if something goes wrong, for ...
13
votes
6answers
6k views

Try/Catch/Log/Rethrow - Is Anti Pattern?

I can see several post where importance of handling exception at central location or at process boundary been emphasized as a good practice rather than littering every code block around try/catch. I ...
1
vote
3answers
355 views

Should a file reader library API throw exceptions?

I am developing a (Java) library providing an API to read a file in a specific format into an object. The format is basically a map, and specifies valid values for some of the keys, and valid types ...
4
votes
1answer
157 views

Is using Option#get really a bad idea here?

I'm working on a Scala project and Wartremover shows an error about Option#get usage in my code: Option#get is disabled - use Option#fold instead While I do understand how get should often be ...
3
votes
2answers
117 views

What are common/best practices for frameworks handling standard third-party exceptions?

Amongst other things in my life, I'm writing a framework in PHP to manage a slew of common problems I come up against in every project I tackle. The framework is currently very data-centric, with the ...
11
votes
5answers
900 views

How to design exceptions

I'm struggling with a very simple question: I'm now working on a server application, and I need to invent a hierarchy for the exceptions (some exceptions already exist, but a general framework is ...
-1
votes
3answers
322 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): ...
-1
votes
1answer
249 views

Difference between Exception “Ducking” and “Swallowing”

I came across a tutorial which says this code is Exception Ducking public class SomeClass { void doTask() { try { //..Some Exception prone code } catch(Exception e) { } }} ...
5
votes
8answers
2k views

Ignore exception when closing a resource such as a file?

From Effective Java 2e by Joshua Bloch, An example of the sort of situation where it might be appropriate to ignore an exception is when closing a FileInputStream. You haven’t changed the state ...