• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

Apps throw exception

AlexeyS

Newbie
Hello, i have a question about exceptions. This is my code.

If(var="test") {
ok:)
} else {
throw exception , stop the program. How can i throw exception here, when var not equal to "test"?
};

Thank you very much
 
I created as you told me, but still i have a problem, the app crashed. Android ask to add try catch. It' s still dosn't work. Thank you.
This is my code:
public class MyException extends Exception {
public MyException(String message){
super(message);
}
}


if () {
}else {
try {
throw new MyException("ErrorError");
} catch (MyException e) {
e.printStackTrace();
}
}
 
The question is, what are you trying to do, and what do you expect to happen?
 
The question is, what are you trying to do, and what do you expect to happen?

I will explain. Inside AssyncTask in DoinBackgraound, i read Json file, and one of varibles i read is Result. Result can get two values : True or False. I f the result true, i can continue to retrieve additional variables, and then go to next step inside AssyncTask, but if the result is false, i have to stop the program, throw exception.
So, i wrote as you told me in first time, i created class MyException :
public class MyException extends Exception {
public MyException(String message){
super(message);
}
}
and inside DoinBackground i did check :
if (Result=="True"){
AllRight - retrieve other data
}esle {
throw new MyException("Error");
}

I know that program enter the else statement, but throw exception doesn't work, the program continue to run and the crashed.
When i wrote as you told, only throw new MyException("Error");, android ask me to add try catch, without it doen't work. But i don't think try catch is suitable in this case. What i should do?Thank you
 
But the code you posted above throws, then immediately catches your exception. That won't terminate the application. If you had just thrown the exception without catching it, then that would have terminated the app.

But if your intention is to stop the application, then why not try the suggestion here, as you asked in a previous thread

https://androidforums.com/threads/exit-from-app.1131286/
 
Back
Top Bottom