我正在做一个小程序,我想要一个在传递空参数时显示错误消息的方法,而不做它的工作。我想
public void doSomething (String) {
try
{
//other
} catch (Exception IllegalArgumentException){
JOptionPane.showMessageDialog(null,"Null argument passed");
}
}
但它不起作用。任何的想法?
更新
看到题外话的大旗,我尽量说得更准确些。我有一个方法必须在数据库中写入它传递的参数。自然存在无意识用户传递空字符串的“风险”,显然我不希望我的数据库由空字符串写入。所以我想解决这个简单的问题。这是我的代码
public void insertTeach(String teachName, int studentsNum) {
try {
String query1 = "INSERT INTO teaching (Name, StudentsNum)"
+ "VALUES ('" + teachName+ "','"
+ StudentsNum + "');";
PreparedStatement statement=con.prepareStatement(query1);
statement.executeUpdate();
JOptionPane.showMessageDialog(null,"Data successfully inserted");
}
catch (Exception ex){
System.out.println("Errore: "+ex);
JOptionPane.showMessageDialog(null,"Error in writing. Try Again.");
}
如果我在 try 的主体中编写 if 语句,则 if 语句将被完全忽略。
public void insertTeach(String teachName, int studentsNum) {
try {
if (param == null) {
JOptionPane.showMessageDialog(null, "Null argument passed");
return;
}
String query1 = "INSERT INTO teaching (Name, StudentsNum)"
+ "VALUES ('" + teachName+ "','"
+ StudentsNum + "');";
PreparedStatement statement=con.prepareStatement(query1);
statement.executeUpdate();
JOptionPane.showMessageDialog(null,"Data successfully inserted");
}
catch (Exception ex){
System.out.println("Errore: "+ex);
JOptionPane.showMessageDialog(null,"Error in writing. Try Again.");
}
我必须做什么?