定义一个对象类型的引用,并将其初始化为null,然后通过这个引用调用某个方法,并通过try-catch语句捕捉出现的异常。

解决方案 »

  1.   


    Object o = null;
    try {
       o.toString();
    }catch(Exception e) {
       e.printStackTrace();
    }
    当然Object的toString方法没有抛出异常
    这只是个假设
    纯属例子
    你也可以定义一个类
    在该类中定义一个方法
    方法内部throw new Exception();
    并在方法后throws Exception
    这样这里再调用该方法的时候就需要抛出异常了!!
      

  2.   

    public class Test
    {
        public static void main(String[] args)
        {
            arithmetic();
            outOfbounds();
            
            try
            {
                notEnglish();
            }
            catch (NotEnglishException e)
            {
                e.printStackTrace();
            }
        }
      

  3.   

    private static void arithmetic()
        {
            try
            {
                int i = 10, j = 0;
                System.out.println(i / j);
            }
            catch (ArithmeticException e)
            {
                e.printStackTrace();
            }
        }
        
        private static void outOfbounds()
        {
            try
            {
                int[] arr = new int[1];
                System.out.println(arr[1]);
            }
            catch (ArrayIndexOutOfBoundsException e)
            {
                e.printStackTrace();
            }
        }
      

  4.   


    public class Test {
    public static void main(String[] args) {
    //定义一个String对象类型的引用,并将其初始化为null
    String s = null;
    //try-catch语句捕捉出现的异常
    try
    {
    //调用s引用的去空白方法
    s.trim();
    }
    catch(Exception ex)
    {
    System.out.println("捕获的异常" + ex.toString());
    }
    }
    }