Java 我在尝试捕获NullPointerException的方法时遇到问题。
代码:Java 我在尝试捕获NullPointerException的方法时遇到问题。,java,Java,代码: 在第二个捕获中,您有一个语法错误: 改变 package exceptiona; import java.io.IOException public class ExceptionTest { @SuppressWarnings("empty-statement") public static void main (String[] args) { // call exceptionA try{ throw new ExceptionA();
在第二个捕获中,您有一个语法错误: 改变
package exceptiona;
import java.io.IOException
public class ExceptionTest {
@SuppressWarnings("empty-statement")
public static void main (String[] args)
{
// call exceptionA
try{
throw new ExceptionA();
} catch (Exception e){
e.printStackTrace(};
System.out.println ("threw Exception A")
// call exceptionB
try{
throw new ExceptionB();
} catch (Exception e) {
e.printStackTrace(};
System.out.println ("threw Exception B")
// throw a NullPointerException
try{
throw new NullPointerException
} catch (NullPointerException){
nu
}
// throw IOException
try{
throw new IOException();
} catch (IOException io){
io.printStackTrace();
}
}
}
到
您的语法有点不正确使用此语法:
e.printStackTrace();
在这之后你用了一个词叫“nu”
您有几个语法错误:
try{
throw new NullPointerException(); //missing ();
} catch (NullPointerException np){
//nu ?
System.out.println("threw NullPointerException");
}
为了开始编码,您一定要学习java语法
参考一般来说,您应该避免捕获NullPointerException,因为它们是运行时的,并且显示错误的代码逻辑
您应该做的是确保不对不应为null的方法提供null参数。您的问题是什么?e.printStackTrace(};这是错误的。更改为e.printStackTrace();Catch NPE?一般来说,不应该捕获运行时异常。这些异常很可能意味着代码逻辑错误。而且,这不会编译。问题以字符
“?”
结尾。在第一个Catch中可以找到相同的错误,前两个Catch块都没有右括号,在NPE Catch块中也没有右括号,nu
不是一个有效的语句。是的,代码中有很多问题。从整个程序抛出和捕获异常的事实来看,这更像是学习try、catch和throw的练习。OP捕获NPE的事实不是问题。
// throw a NullPointerException
try{
throw new NullPointerException();
} catch (NullPointerException npe){
npe.printStackTrace();
}
try{
throw new NullPointerException(); //missing ();
} catch (NullPointerException np){
//nu ?
System.out.println("threw NullPointerException");
}
// throw a NullPointerException
try{
throw new NullPointerException();
} catch (NullPointerException npe){
npe.printStackTrace();
}
public class ExceptionTest {
@SuppressWarnings("empty-statement")
public static void main(String[] args) {
// call exceptionA
try {
throw new ExceptionA();
} catch (Exception e) {
e.printStackTrace();
System.out.println("threw Exception A");
// call exceptionB
try {
throw new ExceptionB();
} catch (Exception e1) {
e1.printStackTrace();
System.out.println("threw Exception B");
// throw a NullPointerException
try {
throw new NullPointerException();
} catch (NullPointerException nu) {
}
// throw IOException
try {
throw new IOException();
} catch (IOException io) {
io.printStackTrace();
}
}
}
}
}