class BadFoodException extends Exception{
//Do something
}
class Reader {
private String food1;
private String food2;
public static void main(String args[])
{
Reader m = new Reader(args);
for (int i=0; i<args.length; i++){
try
{
m.checkfood(args[i]);
}
catch(BadFoodException e){System.out.println(args[i]+ " caught");}
}
}
private Reader(String [] args){
food1=args[0];
food2=args[1];
}
void checkfood(String food) throws BadFoodException
{ if( food == "banana")
throw new BadFoodException();
System.out.println(food + " passed through.");
}
}
Run Code Online (Sandbox Code Playgroud)
我正在通过命令行传递两种食物 - 香蕉和芒果.当食物是香蕉时,checkfood方法应该抛出异常..芒果应该通过.然而两者都是通过而不是?为什么?