0
why would I use the throw statement for?
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());
}
}
}
+ 1
You can use it to throw an exception