I’m trying to understand the correct structures of a program here to facilitate everything. Basically where to “put” things.
For example:
You have 2 classes.
Class 1 is your main.
Both classes have many methods.
Class 1 calls for an instance of Class 2 and runs a method. This method is supposed to return a value.
Question 1:
Should I have a try/catch block INSIDE this method (in Class 2)?
Question 2:
Should the try/catch block be where I call the method (in Class 1)?
try
method();
catch
...
Question 3:
When executing the method that is in Class 2, when it comes to returning a value, should I ever return “an error code” and then deal with this code in the calling class?
Question 4:
When an error happens and I need to “halt” the program, should I use if/else statements so the code only moves forward if the correct conditions are met or should I use the keyword “break” more often?
Question 5:
The possibilities for errors could be endless, specially if you have medium to large programs. How do you guys deal with unknowable errors which you might encounter while the user is running your program?
Exceptions are just that: exceptional. You shouldn’t be using exceptions for regular program flow. (If you say, “Oh yeah, I expected that”, it probably shouldn’t be an exception.)
Handle the exception where it needs handling. If you can survive the function without that
try-catchblock succeeding, then you should handle it there. Similarly, if you need to wrap some things up, you can also add afinallyblock (usingis similar tofinallyin C#- it compiles down totry-finally, but is not as robust as writing it yourself. It simply calls.Dispose()on the disposable object you specified).But if you need to bail out of that function, or you’re running a string of functions that need to all succeed in your main class, it might be better to do the handling in your Class 1.
Caveat: There are exceptions (ha!) to every rule. As you program more, you can get an intuitive sense of where error handling should be done- but often there will be more than one option and it may not be clear cut.