有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

我尝试捕获java PointException和NullException方法时遇到了问题。

代码:

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) 个答案

  1. # 1 楼答案

    你的语法有点不正确使用这个:

    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");
    }
    
  2. # 2 楼答案

    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();
    
                    }
                }
            }
        }
    }
    
  3. # 3 楼答案

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

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

  4. # 4 楼答案

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

    改变

    e.printStackTrace(};
    

    e.printStackTrace();