0

why would I use the throw statement for?

14th Sep 2016, 4:47 AM
logan fearon
logan fearon - avatar
2 Answers
+ 3
Use it to throw an exception. You could use it with your defind exception too. see the example how to throw WrongAnswer exception in below: class WrongAnswer extends Exception { public WrongAnswer(String message){ super(message); } } class Question{ public void isCorrect(String answer) throws WrongAnswer { if (answer == "bird"){ System.out.println("Correct!"); }else { throw new WrongAnswer(answer + " is a wrong answer"); } } } public class Program { public static void main(String[] args) { Question q = new Question(); try{ q.isCorrect("Monkey"); } catch(WrongAnswer wa){ System.out.println(wa.getMessage()); } } }
14th Sep 2016, 12:30 PM
Tiger
Tiger - avatar
+ 1
You can use it to throw an exception
16th Sep 2016, 12:39 AM
violet