We’re rewarding the question askers & reputations are being recalculated! Read more.
34

Status codes have long gone the way of the Dodo --- made extinct by exceptions, actually. The problem with a status code is that it can be ignored. An exception cannot. Consider these two examples. Status Codes as Return Values First, the "merchant repository" implementing CRUD operations for merchants: public enum MerchantStatusCode { OK = 0, ...


31

First: congratulations, you have rediscovered the error monad. https://hackage.haskell.org/package/mtl-2.2.1/docs/Control-Monad-Error.html Second: as noted in the comments, C# already has the concept of "wrap up either a value or an exception, namely, Task<T>. You can use Task.FromException and Task.FromResult to construct them. Of course Result on ...


29

This question demonstrates why Test-Driven Development (TDD) is a valuable discipline. If TDD had been strictly followed, the answer would have almost presented itself. To demonstrate that, I copied the tests only (not the 'production code') to a code base, and attempted to figure out what the implementation should be in order to pass each test. Keep in ...


26

Exceptions are for exceptional cases I'm trying to learn exception handling in C++. This is a very bad example to learn exceptions. They are meant for situations where you cannot know that there is something wrong. For example if you want to use std::vector<int> but you're out of memory: std::vector<int> vec(4000000000LL); // will likely ...


25

The problem is that runtime errors in VBA are not exceptions, and error-handling in VBA has very little in common with exception handling. RememberErrLine = Erl() The Erl function is a hidden member of the VBA.Information module for a reason - it returns 0 unless the error occurred on a numbered line. And if you're using line numbers in VBA, you have been ...


23

First, use try/catch blocks around parts that can throw exceptions. For example, what happens when an IOException is thrown by the file, perhaps because the data is corrupted and the file exists, but cannot be opened? Second, I don't know what constitutes failure, but an app-closing failure is failure in my book: if(!file.isFile()){ System.err.println(...


23

Reusable methods Notice that you have several methods that essentially do the same thing. Log and both writeCustomErrorLog methods follow the same approach: StreamWriter sw = null; try { sw = new StreamWriter("some file path", true); sw.WriteLine("some string"); sw.Flush(); sw.Close(); catch (Exception ex) { throw ex; } This can ...


23

Networking You have done the classic thing that all people new to TCP do of assuming that whatever NetworkStream.Read gives you will be some meaningful chunk of data: this is not guaranteed, and only 'works' because you are sending tiny packages locally. Basically, if you want this to be a general-purpose and reusable system for sending discrete messages (i....


20

Firstly, your implementation is (arguably) not quite correct: else if((m < 0) || (n < 0)) return -1; The GCD of two negative numbers is perfectly well defined. However, if you really don't want the user to pass in negative numbers, make it explicit in the function signature: unsigned greatestCommonDivisor(unsigned m, unsigned n) Euclid's ...


20

There is little reason to do this. If you include the stacktrace in your logs you already know where the problem exists; the only thing you'd miss is the input which you might know from different channels (and often isn't necessary to figure out the problem). Noting that your example returns void which is probably not what you intended, I should say that ...


19

I'm not a member of the “goto is evil and must not be used under any circumstances” camp. Especially in performance-critical low-level routines, it can be useful from time to time. However, most of the time, the temptation to use goto actually stems from missing a better opportunity to structure the code. In your example, I'd simply re-structure it like ...


18

If you upgrade to Java 7, you can use the new Multi-catch syntax. You could change the first block to: try { fileName = RestServices.getInstance().getClassName(getSourceCodeURI()); } catch (ClientProtocolException | IOException | RestServicesException e) { fileName = "not available"; e.printStackTrace(); } Essentially ...


18

Yeah, sure, I could just get rid of the if's and else's and replace ((Item)list...) with Item item = list... and wrap it all in a single Try{}Catch{}, but I really do hate using Try{}Catch{} unless there is something I am not expecting. And to be honest, using Try{} Catch{} makes me feel lazy and like I'm not doing it properly. That is true. The best ...


18

You could use goto, but you can also just define a function, as the label returns a value anyways. For example, your label FAILED:, would become the following function. public IQueryable<T> Failed() { if (defaultSort != null) { query = query.OrderBy(defaultSort); } return query; } You shouldn't ever use goto for flow control, ...


18

An ImportError instance doesn't have a replace method. You can use e.name instead of messy string replacements. Instead of '%s' % x, it's recommended to use '{}'.format(x). The example output is not what you posted, but actually this: 'Error: Try sudo pip install Crypto' That is, it's surrounded by single quotes, because you wrote as "'some text'". ...


17

try: track, num_tracks = track_info.split('/', 1) except: track, num_tracks = track_info, None Honestly, this is not a terrible solution. But you should almost never use except:; you should catch a specific exception. Here is another way: tracks, _, num_tracks = text.partition('/') return int(tracks), int(num_tracks) if num_tracks else None


17

C would have allowed you to just ignore errors and pretend everything was good. A naïve cat would be very short, but rather unreliable also. A well‐written cat will go and use all the error codes that are returned to produce a useful result. Python and similar languages would raise exceptions in these cases, leading to you getting tracebacks in case of ...


14

There are quite a few points of improvement in this code. Networking is not my speciality, but I can give you several suggestions on code improvement. First, a quick word on naming: Type names in ALL_CAPS (i.e.: SERVER) are a bad choice. Most programmers associate this kind of naming with constants and macros. For C++ types, you should probably use ...


14

It depends on how you wish to present the error state to your end user. A rule of thumb: Always log the original exception (which is lower-level and very often quite technical and would scare nontechnical users). But wrap the exceptions in more user-friendly exceptions (higher-level) with messages that are in plain language and easy to understand for the ...


14

The program cannot be made totally unbreakable. for(int i = 0; i < N; i++){ average += nums[i] / N; } for(int i = 0; i < N; i++){ total += nums[i]; } average = total / N; There are two ways to compute the average of a list of numbers, both of which can be broken: The method you use: divide each number by the size of the list, then add it to ...


14

Memory management You never delete[] arr;, which leaks memory. Not a good thing! There are multiple ways to fix this: Adding correct calls to delete[] arr; in the right places (remember exceptions, assignments and so on!), which is rather bug-prone. Also, new T[size] default-constructs size objects of type T in the contiguous memory. This requires T to be ...


13

There's lots of place for improvement. retry: // (1) try { if(getaddrinfo(NULL,INIT_PORT_NUMBER,&hints,result) < 0) { DWORD error = GetLastError(); throw new ERR(error); // (2) } freeaddrinfo(&hints); }catch(ERR& e) // (3) First (1), don't use goto in C++. There are (arguably) places where it improves things, ...


13

You have asked a lot of questions and omitted the most important question. Is the security system I have developed secure against attacks? Absolutely it is not. There is an enormous security problem here. Random is pseudo-random, not crypto-strength random, and that means that it is easy for an attacker to make good guesses about the output of this ...


13

I don't like the idea of using an all-in-one struct. You will have to do more maintenance: every time you create a function that returns different values, you have to create a new struct. Further, I think the struct return value will confuse the user. Everyone is familiar with the basic types, so they will immediately know how to use a function just from it'...


12

These unhandled exceptions smell very bad. Storing error messages in the place of data also is not a good sign (like fileName = "not available"). Anyway, some notes: You could extract out a RestServices restServices = RestServices.getInstance(); variable. You should create constants from repeating Strings, like "not available", "no before source code ...


12

Yeah, I'd probably redo it with an actual condition. That way, intent looks clear and is not dependent on internal code to break, continue, etc. const int NumberOfRetries = 3; var retryCount = NumberOfRetries; var success = false; while(!success && retryCount > 0) { try { AttemptToConnect(); success = true; } catch(...


12

Error Handling Your error handlers look much cleaner (and ultimately safer) than before. I also like your GetErrorSoure() routine and the "CleanExit:" name of the labels. Very concise. (<-Read as, "I'll be 'borrowing' more of your code'). I see a small issue in your OpenFile() routine. You should probably set OpenFile = False prior to re-raising the ...


12

The only coupling I can see with MSAccess-specific vba is in your exampleCall (why is it Private anyway?): Dim prj As vbProject Set prj = VBE.ActiveVBProject Your code works perfectly fine with Excel vba if you take in a VBProject parameter: Public Sub exampleCall(project As VBProject) If this code lives in a class module called Ext, I can then do this ...


12

Make a function that writes an error message (String) to the console, then exits with failure error code. But I'm not sure whether this would mess up your returns and overall control flow. Other than that, I don't know. Yes, you can golf the string to "Unable to open X : " + x + ", it does not exist on the server", but all you're doing is making the error ...


Only top voted, non community-wiki answers of a minimum length are eligible