Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

Java Java Objects (Retired) Delivering the MVP Arrays and Command Line Arguments

How to not have your code crash when throwing exceptions?

context: I'm in an intro to computer science course and i'm not in charge of writing tester code. The professor does that. A requirement for the program is not to have it crash. It seems when you throw an exception the program crashes, and it is only in the tester class that the code exist to manipulate exceptions -- How do I then throw an illegal argument exception and not have the program crash but re-prompt the user for info? Do I write the try- catch code in the Game logic class?

1 Answer

Sam Chaudry
Sam Chaudry
25,519 Points

Hi Damion,

I've had a think about it and this a crude solution but it should put you on the right line thinking - it's hard for me to see what you are doing without seeing the code base.

1.Firstly I would write a public method in the tester class called something like 'promptUserAgainFromException', you can set whatever parameters you want, and for example I have used the return type of string.

So for example in the Tester class:

public string promptUserAgainFromException(){

string errorMessage = "Sorry details are incorrect, please try again";

return errorMessage;

}

  1. Then create a new instance of that class in the Game Logic class (I assuming this is the main body of the programme - from what you have written), create a new instance of this 'Tester' class like so and now you have access to the methods for the try catch block.

  2. So your code could like this in the Game Logic Class:

tester Tester = new tester();

try{

  • Do something here if name and address is correct etc

}catch(illegalArgument exception){

 string errorOnScreen =  Tester. promptUserAgainFromException();

}

Since your method returns a string you can put this on the screen and inform your user as to re-enter your details on screen. My method is a simple example of what can be done, I hope this helps and gets you on the right line to get your programme working.

Thanks Sam!