Open Side Menu Go to the Top
Register
try/catch try/catch

06-16-2020 , 08:38 AM
Why is try/catch used? Is it just if there are too many possibilities for errors?
try/catch Quote
06-16-2020 , 09:56 AM
Most likely to catch specific errors...

KeyNotFound in a dictionary
DivisionByZero
CantConnectToDatabase

And the program wont crash, aka, the execution can process as the exception was "handled" you could then log the error or send a feedback to user about the error

Avoid using try catch with a catch all exceptions

Try catch are NOT to be used as logic in your code. But to handle, unexpected specific outcomes...

Theres a lot more to it but generally they can be useful but use them with care
try/catch Quote
06-18-2020 , 12:58 PM
try/catch are used to handle exceptional conditions.

In a tiered architecture, don't use try/catch if that specific layer doesn't know what to do with an exception. For example, some low level like db might throw an exception.

The middle layers will be able to catch those exceptions, but might not know what to do with it. In that case, don't put try/catch in the middle layers--just let the exception bubble up to some higher layer, which can catch exceptions and fail gracefully (i.e., show the user a message rather than bombing out).

OTOH, you might want middle layers to catch and re-throw exceptions. An example of this is some middle database-access layer. You might want it to catch an exception and log it (adding useful information to the log message), then throw it up the stack so the UI can fail gracefully. So, sometimes a layer can't completely handle an exception, but can add some value like logging.

You may have several catch blocks, one for each different specific exception you want to handle. Maybe there are certain cases you can continue, and some cases where you need to error out.

For example, let's say you try to retrieve some data from a configuration. But, you have a default value for non-configured setups. Let's further say that data needs to be converted from a string to an integer.

You might write a try/catch around the conversion, and in the catch log a message like "client X <thing> configuration not set, using <default value>". In theory, someone might see that message and go properly configure client X.*

This illustrates good practices--log all exceptions, and add useful info to the message (in that case the client id X) so someone can at least have a chance to find the offending data and fix it.

stlows is correct in saying that "logic by exception" is not a good pattern, and should be avoided.

Sorry for the long response, but handling exceptions well and building fault-tolerant systems is a deceptively difficult. On the surface, it seems like "make sure to catch exceptions and fail gracefully," but there's a lot more under the hood with doing it well.

*In reality, nobody's looking at the logs, and that will never be addressed.
try/catch Quote
06-18-2020 , 04:58 PM
Thanks for the responses.

I guess maybe it was just the wording, like "try this, see what happens" seemingly a 70% or so chance of working. Instead of run/catch or something like that.

The architecture doesn't slow anything down, right? It's just running code, it doesn't have to check/loop or anything. So I guess maybe it was just the wording that confused me.. and I guess I started reading a bunch about maybe how "unreliable" or "unprofessional" the pattern was.
try/catch Quote
06-19-2020 , 09:52 AM
I'm not sure what your second paragraph means.

I suppose it depends on your environment and framework, but no, nothing should be affected from a performance standpoint.* If you're using a high-level language like C# or Java, remember everything is compiled and then executed in the VM. So, because things are compiled JIT, there might be occasional performance hits as the stack of classes is compiled (typically on the first execution, but it may fall out of cache over time).

But, once it's compiled, it should execute at the same speed whether you're in an exception-handling block, or working through the try block. It's just code.

*Of course, performance can be degraded by the actual actions you take when executing code. If your logging is slow, exception handling will be slow, of course. But, that's not a problem of exception handling, it's a problem of logging.
try/catch Quote
06-19-2020 , 11:23 AM
Ok, that answers my questions.

By the way when you say high level language, like I am using C#.. what are the thoughts of the lower level programmers of the programmers that use scripting? Is it less professional, lower difficulty, different skill set?
try/catch Quote
06-19-2020 , 11:44 AM
When I write "higher-level language", I mean something that helps with memory management etc like C# or Java (others I'm not familiar with too) as opposed to C, where you have to manage memory yourself (i.e., it's closer to machine language or assembler).

I don't have that much background with scripting. I think a lot of it is using the right tool for the job. If you're wanting to manipulate a document in the browser, javascript/jQuery are probably the right tools for you (as opposed to posting back to the server and re-delivering an entirely new form, you might be able to keep it all on the client).

Just like anything, I'm sure there are people who create very professional, solid code with scripting languages, and those who write shitware which doesn't scale and is bug-ridden. Same with C# or Java.

You seem as if you're younger and starting out. If you're a developer (i.e., not just some guy who likes programming), I hope you're lucky enough to find smart people to mentor you as I did. In other words, not just "write code this way," but explain why that architecture works, why things are separated the way they are, etc.

As you career progresses, you'll probably be shocked at how many true hacks there are out there--cut and paste monkeys, hard-coding stuff, etc, etc.
try/catch Quote
06-19-2020 , 01:42 PM
What do you program in C, like robots? Are car ECUs in C? How difficult or easy is C++ if you know C well?
try/catch Quote
06-19-2020 , 02:31 PM
I can't speak to C++. My understanding is it's one of the bases of the more modern OO frameworks, extending C structs to have the notion of methods. But not sure.

I haven't programmed in C for 20+ years. It was just LOB applications, generating web content IIRC.

Then really smart people figured out nice frameworks, and we left that stuff behind.

On a side note, today is my last day as a developer--I'm retiring. We'll see if it sticks, or if I go back to work after a time-off period.
try/catch Quote
06-19-2020 , 06:34 PM
Congrats, does that mean more time for poker?
try/catch Quote
06-23-2020 , 04:36 PM
Quote:
Originally Posted by yellow6host
So I guess maybe it was just the wording that confused me.. and I guess I started reading a bunch about maybe how "unreliable" or "unprofessional" the pattern was.
What sometimes happens when people don't understand what its for is they put try/catch in every function and do one of the following:
1.) they just rethrow the exception..so its wasted code and doesn't add any value and I'm pretty sure destroys your call stack.
2.) they have someone telling them that they are getting an error in the code and they don't want to see the error any more, so they just silently swallow any errors that are happening by not doing anything with the error.

So as others have said, just use try/catch if you're actually planning to do something (like logging) with an error that happens.
try/catch Quote
06-23-2020 , 04:43 PM
Quote:
Originally Posted by yellow6host
What do you program in C, like robots? Are car ECUs in C? How difficult or easy is C++ if you know C well?
Wiki article on C gives good synopsis on C Uses

I haven't done C or C++ since college but IIRC their syntax is very similar but C++ was much more geared around object oriented programming.
try/catch Quote
06-25-2020 , 11:48 AM
There are a few major cases for try/catch that I can think of

1. there are some *expected* errors that could occur, and you know how to handle them. For example let's say you want to download from a URL. You might fail to connect, it might fail to resolve the address, it might time out, it might give an error code. Many of these are recoverable - wait a second and try again. Catching those expections gives you an option to gracefully recover

2. you may be doing something where you feel confident that EVEN if something fails, it's OK to continue. Like maybe you want to email the results of a process to someone, but sending the email fails. But you want to continue on anyway because finishing the job is more important than sending the notification

3. you want to handle errors elsewhere. It's really common in web architectures that you want to handle all otherwise-unhandled errors at a top level, so that you can produce a "nice" looking error page. So you might have a try/catch at the highest level that, when triggered, returns an error page.

There are some other cases. Python has veered away from this a bit, but it is still common to use try/catch as a flow mechanism in python, such as

Code:
try:
   a = int(x)
   isint = True
except ValueError:
   isint = False
i.e. to determine if x is something that could be "cast" to an integer, try to do it. If it succeeds, it is, if it fails, it isn't.

I find this pretty annoying and avoid it if I can. Another one is

Code:
a = next(x for x in mylist if len(x) > 10)
Let's say mylist is a list of strings and I want the first one that is longer than 10 characters. This works fine IF there is such an element. If there isn't, it'll raise a StopIteration exception. So if I want to detect whether or not the element exists I have to catch the StopIteration exception. IME a better way to do this would be to return a sentinel value that means "no result was found"
try/catch Quote
07-20-2020 , 01:20 PM
Try catch is used to maintain the normal flow of the program irrespective of errors or exceptions which might occur during the execution of the program.

You might say Why exception occurre? Typically Exception can occur due to Wrong logic implementation, wrong input or any connection issue can cause exception.

You can read more here
https://corevoila.in/net/c-sharp/exc...g-in-c-part-i/

https://corevoila.in/net/c-sharp/exc...dling-part-ii/
try/catch Quote
09-09-2020 , 06:07 PM
If a language has try catch statements, you can think of every function returning a tuple with a hidden variable that indicates whether there was an error, in addition every time a function is called, a hidden statement first checks whether this variable is positive, and then proceeds to return early and return with an error. Since a function both checks the error value of its called methods and returns an error if it exists, the error effectively travels up the call stack until the entry point is reached, in which case execution is halted.

You can then think of a try statement as overriding the typical hidden statement of every function call within the try block. Instead of checking for the error variable and returning early if it's true, execution now exits the try block and continues to the catch block instead. If the end of the try block is reached without an error in any of the functions, the catch block is skipped.

It might seem silly and complicated to use this extra logic path, in fact, some languages like Go choose to make this model explicit and functions look like this:
Code:
error, value = divide(3,0)
if error:
  print("division by 0")
Some other languages, like Java, provide tools to limit the added complexity of exceptions by forcing exceptions to be declared as part of the function's return type, while maintaining the implicit control flow:
Code:
int divide(int x, int y) throws Exception{
   //...
}

  //this compiles
String goodDivision(String command) throws Exception{
  int x,y = parse(command);
  return String(divide(x,y));

}

// This fails because there is a potentially unhandled exception.
String badDivision(String command){
  int x,y = parse(command);
  return String(divide(x,y));
}

String okDivision(String command){
  int x,y = parse(command);
  try{
    return String(divide,x,y));
  }catch{
    return "Error";
  }
}
The purpose of exceptions is purely semantic, they convey information about the unhappy path, and they cluster all possible problems that you do not wish to handle. As a programmer you will use classical control flow for most scenarios you can think of, and when these scenarios start becoming rarer and rarer, you just bunch them up as Miscellanea and move on. For example:
Code:
if address in country:
  approve()
else address in foreginCountries:
  reject()
else address in bastardNations:
  nationalize()
else address in moon:
  reject
else:
  log("I don't understand the address: " + address)
  throw Exception

Last edited by _dave_; 09-10-2020 at 03:51 AM. Reason: [code] tags
try/catch Quote

      
m