0

我正在做一个小程序,我想要一个在传递空参数时显示错误消息的方法,而不做它的工作。我想

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.");
}

我必须做什么?

4

2 回答 2

0
public void doSomething (String s) {
    if (s == null) {
        JOptionPane.showMessageDialog(null,"Null argument passed");
        return;
    }
    // actual work
}
于 2013-09-04T23:13:30.443 回答
0

我认为您想要做的实际上是捕获 aNullPointerException而不是 a IllegalArgumentException。这是因为IllegalArgumentException当有人将 anull作为参数传递时不会抛出 an,因为null它不是非法参数。所以你的代码应该看起来像 -

public void doSomething (String) {
try
{
   //other
} catch (NullPointerException e){
    JOptionPane.showMessageDialog(null,"Null argument passed");
}
}

或者更好

public void doSomething (String) {
    if(String == null)//do error stuff
}
于 2013-09-04T23:16:45.483 回答