KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I've used try and catch statements as an easy way to keep my code running without things crashing (I would wrap everything in a big try). Recently, I've wanted to start using try and catch statements more correctly. Here as an example I have questions about: public class Ninja{ Ninja(){ } public void ThrowShirikin(int numberOfShirikins){ try{ if(numberOfShirikins == 0){ throw new System.ArgumentException("Invalid number of shirikins"); } //Throw shirikin } catch(ArgumentException e){ MessageBox.Show(e.Message); } } } In the above Ninja class, the entire contents of my ThrowShirikin method is contained in a try loop. Since there is only one opportunity for an input error (in this case, when numberOfShirikins == 0), shouldn't only the lines of code that check for this be contained in the try loop? See below: public class Ninja{ Ninja(){ } public void ThrowShirikin(int numberOfShirikins){ bool errorsExist = false; try{ if(numberOfShirikins == 0){ errorsExist = true; throw new System.ArgumentException("Invalid number of shirikins"); } } catch(ArgumentException e){ MessageBox.Show(e.Message); } if(!errorsExist){ //Throw shirikin } } } ^But what I have here seems a bit clunky. Any suggestions and input on how I'm understanding the use of try catch statements? Thanks! Edit: Or I could do something like this so the //Throw shirikin code never executes if there is an invalid value for numberOfShirikins?: public class Ninja{ Ninja(){ } public void ThrowShirikin(int numberOfShirikins){ try{ if(numberOfShirikins == 0){ throw new System.ArgumentException("Inval
Tags (comma-separated)
Save Edits
Cancel