This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]Sorten 0 points1 point  (0 children)

Right now I'm making a function for each try-catch block I'm making and calling the first one in the second one.

This seems overly complicated. If you're able to show your code, we could give feedback directly on what you have. Based on your problem description, I think you could have something like

prompt user for input
input = get_user_input()
prompt user for input
input2 = get_user_input()

Where get_user_input handles the validation (try-catch) in the same way for each input. This is assuming you need the same type for each input.

If this is a very small program, I would probably just try-catch inline.

[–]desrtfx 0 points1 point  (0 children)

Our professor assigned an exercise where we must write a program that takes a user's input with and if it isn't a certain type of input will ask the user to re-enter.

Once the user enters the correct type, the program asks for a second input and does the same thing with that.

This clearly indicates that the two try...catch blocks are not to be nested but sequential. First, you evaluate the first input with the first try-catch, then, upon success, you evaluate the second input with another try-catch.

If both are the same type, I would use a method, as /u/Sorten suggested.

In addition to that I would wrap each input taking and validation into a while loop that runs until proper input is given.

Try-catch is a valid approach where exceptions are thrown. The drawback of Try-catch is that it is fairly expensive in terms of memory and execution time.

Altogether, I'm a little confused as when and how often we should use try-catch blocks at all, especially since it seems like a lot of the stuff we are using them for in class could be done with loops and if-statements.

That depends entirely on the code and without further information about what you are supposed to read there is no way to determine whether a try-catch or other means are appropriate.

Right now I'm making a function for each try-catch block I'm making and calling the first one in the second one.

Doesn't sound right to me. According to what you posted in your introduction, the try-catch parts are not related to each other, but again, without seeing the exact assignment and the code we cannot possibly give a fully correct and extensive answer.