2

I'm currently trying to have it display another message only if an Exception isn't caught when using Try Catch. Right now it'll display an exception, and then my message after that. So I was just asking for some tips on how I could go about doing that.

Here's my code.

try { } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { MessageBox.Show("Solution Downloaded in C:/dwnload/working"); } 
3
  • place it outside of the try? Commented Jun 12, 2018 at 14:28
  • 1
    @Gaterde - no, then it would show always as well Commented Jun 12, 2018 at 14:32
  • 1
    I guess like the answer below placing it inside the try at the bottom should work because if it hasn't hit any exceptions by that point it worked. Commented Jun 12, 2018 at 14:34

3 Answers 3

4
 try { // Do Work // when we get here: success! Without errors! MessageBox.Show("Solution Downloaded in C:/dwnload/working"); } catch (Exception ex) { MessageBox.Show(ex.Message); } 
Sign up to request clarification or add additional context in comments.

Comments

4

You should just do it after the code that can throw an exception in the try statement.

try { // do operation that could throw exception // display message } catch (Exception e) { // catch code } finally { // code to run at the end regardless of success/failure } 

Comments

2

Simple refactor the message as a variable. Assign the success message at the end of the try block.

in the catch block, assign the error message.

Then display the MessageBox, in the finally block or after, as you prefer.

 string message; try { // at the end of try block message = "Solution Downloaded in C:/dwnload/working); } catch (Exception ex) { message = ex.Message; } finally { // in general, keep the finally code as the minimum needed for sanity cleanup. } // If you rethrow your exception, and still want to show the message box, then might have a reason for wanting this instruction back inside the finally block. MessageBox.Show(message); 

1 Comment

exactly i agree with you. Finally is for important cleanup that must be done Actually, I started writing this answer with the message box outside. But it would not display message box if the exception is rethrown, this code might be an oversimplification of what's actally in the catch block . So i put it back inside the finally block, the time to write a remark on that

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.