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

learn more… | top users | synonyms

6
votes
2answers
171 views

Why shouldn't a method throw multiple types of checked exceptions?

We use SonarQube to analyze our Java code and it has this rule (set to critical): Public methods should throw at most one checked exception Using checked exceptions forces method callers to ...
2
votes
1answer
57 views

Under which circumstances does it make sense to lose track of where an exception was thrown from?

Is there any valid reason why a catch block on a lower layer would throw back an exception caused by a higher, unknown layer using the following syntax: throw ex; ... rather than: throw; ... ? ...
0
votes
1answer
38 views

Advice needed on rethrowing an exception

Consider the following c# code: public class ExceptionManager { public static void TreatException(Exception ex) { if (ShowAndContinue(ex)) // display a user-friendly ...
25
votes
9answers
3k views

Should I accept empty collections in my methods that iterate over them?

I have a method where all logic is performed inside a foreach loop that iterates over the method's parameter: public IEnumerable<TransformedNode> TransformNodes(IEnumerable<Node> nodes) { ...
2
votes
1answer
93 views

Exceptions in ANSI C

Would it be possible to implement exception mechanism in pure ANSI C similar to the one used in popular OOP languages (with familiar try-catch-finally clauses)? If yes then how? I'm especially ...
0
votes
0answers
20 views

How to stop connecting to a server after n unsuccessful attempts? [migrated]

Here is the problem. I am trying to connect to a server. If the connection goes through, then print an apt message. If the connection does not go through, try for a total of n times. And quit after ...
1
vote
2answers
68 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 ...
-2
votes
0answers
42 views

What is better for error trapping? Return values or Exception handling [duplicate]

The scenario is that there are so many error traps needed in your code. As far as I can see, the pros and cons of these two methods are: Return values pros: more run-time efficient; cons: the ...
-2
votes
0answers
17 views

How to change the return message of Exception.getMessage()? [migrated]

I need to change the return message of the method getMessage() , for instance, i have an ArithmeticException, and when i write: try{c=a/0;} catch(ArithmeticException excep){System.out.println( ...
0
votes
1answer
117 views

Should I throw std::bad_alloc?

I am allocating memory on the stack, and distributing it manually to shared pointers. I end up doing something like this at startup (I've simplified it by ignoring alignment issues): char pool[100]; ...
1
vote
4answers
127 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: ...
1
vote
1answer
224 views

Exceptions: What to handle, what to throw

I have a custom configuration reader which performs various functions on top of .NET's CloudConfigurationManager and ConfigurationManager implementations, such as caching, type conversion, etc. The ...
1
vote
1answer
56 views

Exception class for each exception or for all framework

I am developing a framework and it can generate various types of exceptions. Initially I'm working with a single exception class that indicates that something went wrong inside the framework. However, ...
3
votes
4answers
399 views

Java - Is it possible/good idea to reduce chance of crashing by catching Error?

I have a class the implements A which will run a certain method of class B. There is a requirement that this A should never crash when running this operation (which is not possible, right?). To ...
6
votes
4answers
785 views

Why design a modern language without an exception-handling mechanism?

Many modern languages provide rich exception handling features, but Apple's Swift programming language does not provide an exception handling mechanism. Steeped in exceptions as I am, I'm having ...
3
votes
2answers
311 views

How does the JVM handle an exception thrown by the main method?

I understand exceptions, throwing them, handling them, and propagating them to a method lower in the call stack (i.e. throws). What I don't understand is this: public static void main(String[] args) ...
1
vote
3answers
72 views

Logging instance information in Exceptions

During development on a large existing codebase I've started to capture variable values in my Exception logging. For example: public int Foo(int a, int b) { int returnInt; try{ returnInt ...
28
votes
8answers
1k views

Is it okay to use exceptions as tools to “catch” errors early?

I use exceptions to catch problems early. For example: public int getAverageAge(Person p1, Person p2){ if(p1 == null || p2 == null) throw new IllegalArgumentException("One or more of ...
3
votes
4answers
286 views

Is a long list of parameter checks an anti-pattern?

Background: I'm working on an application that will manage backup generators. These generators need to be able to be "linked" together. For example, Generator B might serve as a backup for ...
1
vote
3answers
138 views

Null checking whilst navigating object hierarchies

I had to implement some code which traversed a small object hierarchy to fetch a value and display it in a TextView object (this is Android / Java). I had to do this 6 times to populate 6 TextViews ...
2
votes
1answer
122 views

RefactorException: Good idea or bad idea?

When I'm doing large scale refactors I'm often commenting out the contents of methods and using NotImplementedExceptions for stuff that I still need to refactor. Problem is that this is interfering ...
2
votes
2answers
125 views

Should I throw guard exceptions that will be thrown by internal methods anyway?

I have some fairly simple code (C#): /// <summary> /// Truncates a string to a maximum length. /// </summary> /// <param name="value"> The string to truncate. ...
1
vote
1answer
141 views

Why is Throwable initCause designed to be called only once?

I find it really odd that the initCause method of Java's Throwable class can only be called once, or even not at all (if the constructor accepting a Throwable was used). This makes exception chaining ...
2
votes
1answer
58 views

Is it good practice to use NoStackTrace in scala?

I came across the NoStackTrace mixin for Exceptions in scala. Is it good practice to use it, or should it be considered "internal" to scala and left alone?
0
votes
5answers
282 views

Should we only catch in exceptional circumstances?

Whether error handling by throwing exceptions is good or bad is contentious. Are exceptions as control flow considered a serious antipattern? If so, Why? The common line is that exceptions are for ...
0
votes
4answers
61 views

alerting that an object cannot be deleted (due to constraints)

Assume an application with a rich domain model with many classes (e.g School, Classroom, Teacher, Student, Course, Exam, Submission, ...) linking to each other. Model and links are mapped to the ...
3
votes
1answer
108 views

When to declare @throws with a Scala annotation - abstract parent or concrete implementation?

In this StackOverflow question I asked about the behavior of the @throws annotation in Scala. Now that I understand how it works I want to ask about best practices with using it. Here's a repost of my ...
3
votes
1answer
181 views

Java-Like 'throws'-information in method signature C#

From Java I know that the signatures of methods that can throw exceptions contain a throws block, that contains the Exception(s) that might be thrown. In C# there is no such thing and it is also not ...
3
votes
4answers
205 views

How much data should exceptions hold?

Almost all the exceptions I have ever written have been very lightweight, containing a String message and optionally a throwable. In some situations I have included some application specific enum or ...
4
votes
2answers
104 views

How do you handle specific networking exceptions in Haskell?

I have the following to try and connect to a server: testAddress :: HostName -> Int -> IO (Maybe Handle) testAddress host iPort = do let port = PortNumber $ fromIntegral iPort putStrLn ...
5
votes
1answer
115 views

Why are F# exceptions generally not suffixed with 'Exception'?

In .NET, it is idiomatic to suffix exception types with Exception. But most, if not all, sources I have seen for custom exception types in F# don't follow this idiom. Most seem to use the suffix ...
1
vote
1answer
134 views

Pros and cons of custom exceptions [duplicate]

This may be an pointless question based on opinion, style, and context but I've been racking my brain trying to decide whether or not to make use of custom exceptions and would love to hear some pros ...
0
votes
2answers
256 views

IllegalStateException vs. IllegalArgumentException

In have written a function which expects the caller to pass in a configuration file like XML. Then I parse this given file and extract something which i then return. In this function (at least) two ...
36
votes
11answers
4k views

Are error variables an anti-pattern or good design?

In order to handle several possible errors that shouldn't halt execution, I have an error variable that clients can check and use to throw exceptions. Is this an Anti-Pattern? Is there a better way to ...
0
votes
2answers
140 views

Expected error handling

Let's say I have a social media website. On this website, users can upload several pieces of information about themselves, including their phone number. To implement this, I have a class called ...
0
votes
0answers
84 views

How to void checked exceptions in Java? [duplicate]

I consider checked exception for a design mistake in the Java language. They lead to leaky abstractions and a lot of clutter in the code. It seems that they force the programmer to handle exceptions ...
0
votes
2answers
104 views

What should happen when code is reached that shouldn't be, according to business or logic rules? [duplicate]

I am currently writing an application that isn't huge but will be used through-out my company of 200+ people and external customers about projects we are working on (not software projects), but there ...
2
votes
2answers
144 views

Retried Operation with generic Exception

I am looking for a way to get the logic of retrying an operation in a single method while keeping the exception types of the operation. I.e., the implementation to retry an operation could look like ...
10
votes
6answers
2k views

Should you throw an exception if a method's input values are out of range? [duplicate]

Should you throw an exception if a method's input values are out of range? eg //no imaginary numbers public int MySquareRoot(int x) { if (x<0) { throw new ...
-1
votes
1answer
172 views

How to determine what throws an exception [closed]

Whenever I encounter crashes, the exact type of the exception usually already gives enough info to easily find the culprit. FileNotFoundException will hardly occur while using sockets. Now recently ...
0
votes
1answer
171 views

Is ok to throw exception in normal code path which eliminate a possible programmer error? [duplicate]

I know that exception should be thrown in exceptional case (e.g. out of memory, programmer error). For these cases, I don't need to worry about performance throwing these exception. But what happen ...
2
votes
1answer
201 views

Should we encapsulate everything in a try{} block in a Try object?

Why can't I make a class for a Try including what I try and then run that in the try {} block? Why is it impractical? class DBConnectTry extends Try { TryResponse response[] attempt(TryObject ...
0
votes
3answers
85 views

Should I use an Exception in a case like this? [duplicate]

I have a Windows service with a fluent interface like this: aRequest = Repository.getRequest() .createProcess() .validate(); Sometimes getRequest() could ...
1
vote
3answers
244 views

Exception when logging exception: is it correct to ignore them?

My question is specific to php, but i think it can be useful in other languages. I log into a table all the exception a code can throw: try{ //Some code } catch (Exception $e) { $log = new ...
3
votes
5answers
780 views

How should I handle exception that *should* never be thrown? [duplicate]

What is the best way to handle errors that shouldn't ever happen? My current way to do this is to throw an exception if the 'thing that shouldn't happen' does happen, like so: /* * Restoring from a ...
3
votes
1answer
168 views

Should I assert in packages? [duplicate]

I have read a few asserts vs exception questions already; I ask specifically about package visible classes though. When you write a package, the classes marked with "public" are exposed to the ...
-1
votes
1answer
165 views

Functions returning either “OK” or “error message” instead of procedures

I have joined writing middle-size multi-purpose database application as co-lead. It currently has about 150 tables (and growing) and overall functionality you can imagine as very small ERP. At many ...
14
votes
1answer
874 views

Is it fine to make a default constructor unusable?

Specifically asking about the default constructor Given that the constructor initializes all the data for an object, if I create a class that can't be used without proper initialization, is it not ...
3
votes
4answers
315 views

Should exceptions do things other than tell the user something went wrong?

I created a general class that accepts a string when it is constructed, and it spits out that string when a user calls what(). This is all it does; on throw, it returns the initializing string. ...
1
vote
1answer
265 views

Separate namespace just for exceptions?

I was doing a code review and came across something odd which I've never seen before. The developer decided to create a sub-namespace just to contain all the assembly's exceptions. I thought I had ...