-5

代码:

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

    }    
}        
}
4

5 回答 5

2

您有几个语法错误:

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

为了开始编码,您绝对应该学习 java 语法。

请参阅此处获取入门教程

于 2013-08-02T13:56:19.403 回答
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();

                }
            }
        }
    }
}
于 2013-08-02T14:02:39.793 回答
1

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

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

于 2013-08-02T13:57:38.890 回答
1

在第二个捕获中,您有一个语法错误:

改变

e.printStackTrace(};

e.printStackTrace();
于 2013-08-02T13:54:26.373 回答
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");
}
于 2013-08-02T13:56:11.390 回答