JOptionPane:在try-catch语句中按null输入取消键时不会抛出NullPointerException

时间:2018-12-06 00:10:53

标签: joptionpane

当在JOptionPane上按下“取消”并且输入字符串为null时,以下代码将引发NullPointerException:

JOptionPane renamePane = new JOptionPane();
String s = renamePane.showInputDialog(null, "New layer name: ");

->在JOptionPane上按“取消”,并且输入为null时,以下代码未捕获NullPointerException:

JOptionPane renamePane = new JOptionPane();
String s = "anything at all";
try {    s = renamePane.showInputDialog(null, "New layer name: ");   }
catch (NullPointerException npe)
{
     System.out.println("NP caught, returning");
     return;
}

->不会执行print语句,但是s设置为null。为什么?

1 个答案:

答案 0 :(得分:0)

JOptionPane.showInputDialog(Component, Object) Javadoc中没有任何地方说当用户取消而不输入文本时抛出NullPointerException

Javadoc:
https://docs.oracle.com/javase/7/docs/api/javax/swing/JOptionPane.html#showInputDialog(java.awt.Component,%20java.lang.Object)

返回值为null和抛出NullPointerException是两回事。