我在尝试捕获NullPointerException的方法时遇到问题。

时间:2013-08-02 13:50:43

标签: 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();
    } 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();

    }    
}        
}

5 个答案:

答案 0 :(得分:2)

您有几个语法错误:

// throw a NullPointerException
try{
    throw new NullPointerException();
} catch (NullPointerException npe){
    npe.printStackTrace();
}

你应该学习java语法才能开始编码。

参考here for tutorials to get started

答案 1 :(得分:1)

在第二个catch中,您有语法错误:

更改

e.printStackTrace(};

e.printStackTrace();

答案 2 :(得分:1)

一般来说,你应该避免捕获NullPointerException,因为它们是运行时并显示错误的代码逻辑。

您应该做的是确保不为不应为null的方法提供空参数。

答案 3 :(得分:1)

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();

                }
            }
        }
    }
}

答案 4 :(得分:0)

你的语法稍微偏离了这个:

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

在此之后,您使用一个名为“nu”的单词?

try{
    throw new NullPointerException(); //missing ();
} catch (NullPointerException np){
    //nu ?
    System.out.println("threw NullPointerException");
}