Stack Exchange Network

Stack Exchange network consists of 174 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
6answers
320 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
37 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
113 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
138 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
168 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
595 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
177 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
115 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
133 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
985 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 { ...
1
vote
2answers
744 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
564 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
391 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
203 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 ...
72
votes
10answers
12k 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
218 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
168 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
298 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
573 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
48 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
775 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
114 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 ...
1
vote
0answers
101 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 ...
4
votes
2answers
2k 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
114 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
73 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
77 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 { ...
5
votes
2answers
3k 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 ...
7
votes
6answers
3k 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
248 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
136 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
105 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
738 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 ...
-2
votes
3answers
276 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): ...
0
votes
0answers
34 views

When should assetions and when should Exceptions be used [duplicate]

Assume I am writing a library for calculating the velocity, given two datetime objects and a distance: #!/usr/bin/env python def get_velocity(t0, t1, distance): """ Calculate the velocity. ...
-1
votes
1answer
126 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) { } }} ...
4
votes
8answers
1k 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 ...
23
votes
10answers
3k views

Parameter to control whether to throw an exception or return null - good practice?

I often come across methods/functions which have an additional boolean parameter which controls whether an exception is thrown on failure, or null is returned. There are already discussions about ...
3
votes
2answers
137 views

Exception indicating implementation error

Problem I wonder what best practices are to indicate implementation errors detected at runtime. For example, if you write the following method (in Java): public void doSth(int i) { try { ...
3
votes
2answers
565 views

Error handling and exceptions in a layered (or onion) architecture [closed]

Given an onion architecture, what are the advantages and disadvantages of throwing exceptions in the business logic (which is in the center of the onion) for invalid parameters provided by the user? ...
-1
votes
1answer
152 views

Null Object and Exceptions

Do Special Case or Null Object design patterns still provide value when application behavior, not just object behavior has to change? I was tasked with revisiting an old application and refactoring ...
1
vote
1answer
45 views

What kind of exception of SPL is best suited for file exceptions?

When I use the Exception provided by the SPL the options are limited. So it's hard to pick which exception would be best suited to handle File exceptions. I know the best scenario is to write my own ...
1
vote
2answers
358 views

Function that throws exceptions extending IllegalArgumentException

I have a try/catch block which looks like this : try { geoms.add(convertLineToGeom(ln)); } catch(IllegalArgumentException e) { System.out.println("ligne n°" + counter + " : " + e.getMessage())...
0
votes
0answers
68 views

Can I use exception in “good” case [duplicate]

I have case similar to this: Suppose I have sorted list and I have BTree of samples with their value and indexes. When I search for something, I first look over BTree samples and then I decide where ...
1
vote
1answer
88 views

Catching base Exception to preserve data integrity

I know that often catching all exceptions (C#: catch(Exception exception){...}) is deemed bad practice. However, I believe that there are situations where it is perfectly reasonable to do it. For ...
1
vote
2answers
195 views

Why are there non-catcheable exceptions?

I recently asked a question on SO where I was trying to understand how to catch an exception in a piece of code which runs indefinitely. I was initially expecting that try: ...
-1
votes
1answer
2k views

Spring Exception Handling. Custom exception per Http status?

I'm just designing the exception handling for the REST interface on our Spring server. As we will have multiple REST controllers, a central exception handling is desired. Spring offers the solution ...
-1
votes
1answer
48 views

Handling RuntimeExceptions thrown from Services and Libraries

I am working on a ReST based service which calls other ReST based services and also deals with Persistence in a database. So a typical call might look like Get some data from the database. Make a ...
7
votes
2answers
528 views

What should I do with implementation-specific exceptions?

Let's say I have an interface describing a simple service public interface AccountService { public int getUserId(String userName) throws UserNotFoundException; //... } I've written the ...