Java异常课后习题简答题

教材Java面向对象程序设计(第二版) 袁绍欣 第七章1~5、8

1. “程序中凡是可能出现异常的地方必须进行捕获或拋出”,这句话对吗?

不对。
异常类型是RuntimeException或是其子类,程序方法可以对异常不作任何声明抛出或处理,直接交给调用该方法的地方处理,程序能编译通过,不会对可能产生异常的代码行给出提示。

2. 自定义一个异常类,并在程序中主动产生这个异常类对象。

public class SelfGenerateException extends Exception
{
	SelfGenerateException(String msg){
		super(msg);   //调用Exception的构造方法
	}
	static void throwOne() throws SelfGenerateException
	{
		int a = 1;
		if (a==1) //如果a为1就认为在特定应用下存在异常,改变执行路径,抛出异常
		{throw new SelfGenerateException("a为1");}		
	}
	public static void main(String args[])
	{
		try
		{throwOne();}
		catch(SelfGenerateException e)
	    {e.printStackTrace();}
	}
}

结果:

SelfGenerateException: a为1
        at SelfGenerateException.throwOne(SelfGenerateException.java:10)
        at SelfGenerateException.main(SelfGenerateException.java:15)

3. 借助JDK帮助,请列举发生NullPointerException异常的一些情况。

当应用程序试图在需要对象的地方使用 null 时,抛出该异常。这种情况包括:
调用 null 对象的实例方法。
访问或修改 null 对象的字段。
将 null 作为一个数组,获得其长度。
将 null 作为一个数组,访问或修改其时间片。
将 null 作为 Throwable 值抛出。
应用程序应该抛出该类的实例,指示其他对 null 对象的非法使用。

4. 不执行程序,指出下面程序的输出结果;如果将黑体代码去掉,写出输出结果;如果再将斜体代码去掉,写出输出结果。

public class Test
{
       public static void aMethod() throws Exception{ 
             try{ 
                   throw new Exception();
                  }
              **catch(Exception e){
                    System.out.println("exception000");
                   }**//黑体函数部分

               *finally{
                   System.out.println("exception111");
               }*//斜体函数部分
        }
        public void main(String[] args){
                try{
                        aMethod();
                 }
                  catch(Exception e){
                         System.out.println("exception");
                  }
                  System.out.println("finished");     
         } 
}

输出:

exception000
exception111
finished
去黑体输出:
exception111
exception
finished
去斜体输出:
exception000
finished

5. 不执行程序,指出下面程序的输出结果。

public class Test{
        public static String output ='';
        public static void foo(int i){
               try{
                       if(i==1) {throw new Exception();}
                       output += "1";
                }
                catch(Exception e){
                        output += "2";
                        return;
                 }
                 finally{output += "3";}
                 output += "4";
            }
           public static void main(String args[]){
                   foo(0);
                   foo(1);
                   System.out.println(Test.output);
             }
            }

结果:13423

8. 阅读下面程序,TimedOutException为自定义异常,完成指定方法后面的部分。

public void method()throws TimedOutException
          {
        	  success= connect();
        	  if(success == -1)
        	  {
        		  throw new TimedOutException();
        	  }
          }
posted @ 2019-10-13 14:13  MY知北  阅读(243)  评论(0编辑  收藏  举报