Questions tagged [exceptions]

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

Filter by
Sorted by
Tagged with
1
vote
1answer
32 views

Handling Currency getInstance throwing IllegalArgumentException

I have a class with a (simplified) method which returns a string like this : private String doStuff(String currencyCode, BigDecimal amount){ StringBuilder sb= new StringBuilder(); ...
2
votes
6answers
109 views

How can I change my code to display information about failure of creation of a value object, when I want to process an array of such objects?

Consider class Crate that is a value object. Crate represents a valid 3-dimensional box. In constructor I validate the given parameters, and I throw an exception, if supplied dimension parameters ...
2
votes
3answers
223 views

Are Result objects the cleaner way to handle failure, than exceptions? [duplicate]

I was watching the following video by Vladimir Khorikov, which recommends to "Refactoring Away from Exceptions" pluralsight.com - Applying Functional Principles in C# - Refactoring Away from ...
1
vote
2answers
254 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 ...
0
votes
1answer
125 views

How to output exception messages in GUI applications in order to decouple application code to GUI code?

I want to make GUI applications such that the non-GUI code is independent from the GUI one (let's say I'll use Java 8 and Swing for example). The goal is that I could hypothetically change the GUI ...
0
votes
1answer
163 views

Where would you handle exceptions: controller, service, repository?

I have been having this dilemma from time to time whenever I have to design or start a new project from scratch. I particularly like how Spring framework is organised in terms of classic software ...
1
vote
3answers
91 views

Exception handling philosophy when dealing with batches of input

I am handling a file with 1 million records and my customer creates this file from his code. I might receive hundreds of these files. I have to read these records and ingest them into a database. It ...
-3
votes
3answers
167 views

Try-catch in method or where the method is called? [closed]

I have the following method in Java: public method1() { //does something that might throw an exception } And then another method that calls the method above like so: public method2() { ...
3
votes
5answers
331 views

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

...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 ...
7
votes
6answers
4k views

Why do programming languages not let you use a try block without a catch block? [closed]

Why do languages demand catch blocks when they aren't needed? The compiler or parser complains with this code: try { const utils = require("applicationutils"); } But it is OK with this code: ...
-2
votes
4answers
174 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 ...
44
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
104 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
126 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
109 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
142 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
194 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
342 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
753 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
343 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
519 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
469 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
41 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
384 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
153 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
202 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
712 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
192 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
138 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 ...
7
votes
3answers
1k 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
1k 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
228 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 ...
78
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
234 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
5k 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
237 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
377 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
1k 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
54 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
2k 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
125 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 ...
4
votes
2answers
240 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 ...
7
votes
2answers
6k 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
233 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
110 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
88 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 { ...