zoukankan      html  css  js  c++  java
  • 异常与抛出

    1.请阅读并运行AboutException.java示例,然后通过后面的几页PPT了解Java中实现异常处理的基础知识。

    Java中的异常捕获语句

    Try{

    //可能发生运行错误的代码;

    }

    catch(异常类型     异常对象引用){

    //用于处理异常的代码

    }

    finally{

    //用于“善后” 的代码

    }

    Java 中所有可捕获的异常都派生自 Exception 类,把可能会发生错误的代码放进try语句块中,当程序检测到出现了一个错误时会抛出一个异常对象。异常处理代码会捕获并处理这个错误,catch语句块中的代码用于处理错误。当异常发生时,程序控制流程由try语句块跳转到catch语句块。不管是否有异常发生,finally语句块中的语句始终保证被执行。如果没有提供合适的异常处理代码,JVM将会结束掉整个应用程序。

    2.阅读以下代码(CatchWho.java),写出程序运行结果:

    public class CatchWho {

        public static void main(String[] args) {

            try {

                 try {

                     throw new ArrayIndexOutOfBoundsException();

                 }

                 catch(ArrayIndexOutOfBoundsException e) {

                    System.out.println(  "ArrayIndexOutOfBoundsException" +  "/内层try-catch");

                 }

    运行结果:ArrayIndexOutOfBoundsException/内层try-catch

    发生ArithmeticException

    3.写出CatchWho2.java程序运行的结果

    public class CatchWho2 {

        public static void main(String[] args) {

            try {

                 try {

                     throw new ArrayIndexOutOfBoundsException();

                 }

                 catch(ArithmeticException e) {

                     System.out.println( "ArrayIndexOutOfBoundsException" + "/内层try-catch");

                 }

                throw new ArithmeticException();

            }

            catch(ArithmeticException e) {

                System.out.println("发生ArithmeticException");

            }

            catch(ArrayIndexOutOfBoundsException e) {

                System.out.println( "ArrayIndexOutOfBoundsException" + "/外层try-catch");

            }

        }

    }

    运行结果:ArrayIndexOutOfBoundsException/外层try-catch

    4.当有多个嵌套的trycatchfinally时,要特别注意finally的执行时机。

    请先阅读 EmbedFinally.java示例,再运行它,观察其输出并进行总结。

    public class EmbededFinally {  

    public static void main(String args[]) {  

    int result;

    try {

    System.out.println("in Level 1");

      try {      

    System.out.println("in Level 2");

      // result=100/0;  //Level 2     

      try {    

      System.out.println("in Level 3");

                          

      result=100/0;  //Level 3

                    

    }

                    

    catch (Exception e) {

                        

    System.out.println("Level 3:" + e.getClass().toString());

                    

    }

                    

                    

    finally {

                        

    System.out.println("In Level 3 finally");

                    

    }

                    

                   

    // result=100/0;  //Level 2

                

    }

                

    catch (Exception e) {

                   

      System.out.println("Level 2:" + e.getClass().toString());

               

      }

      finally {

                    

    System.out.println("In Level 2 finally");

               

     }

                 

    // result = 100 / 0;  //level 1

            

    }    

    catch (Exception e) {     

    System.out.println("Level 1:" + e.getClass().toString())     

    }

          

    finally {

      System.out.println("In Level 1 finally")    

    }

    }

    }

    无论是否抛出异常,也无论从什么地方return返回,finally语句块总是会执行,这样你有机会调用Close来关闭数据库连接(即使未打开或打开失败,关闭操作永远是可以执行的),以便于释放已经产生的连接,释放资源。

    5.辨析:finally语句块一定会执行吗?

    请通过 SystemExitAndFinally.java示例程序回答上述问题

    public class SystemExitAndFinally {
    
        
    	public static void main(String[] args)
        {
            
    		try{
    
                
    			System.out.println("in main");
                
    			throw new Exception("Exception is thrown in main");
    
                		//System.exit(0);
    
            
    		}
            
    		catch(Exception e)
    
    	        {
                
    			System.out.println(e.getMessage());
                
    			System.exit(0);
            
    		}
            
    		finally
            
    		{
                
    			System.out.println("in finally");
            
    		}
        
    	}
    
    
    }
    

      

    finally语句不一定要执行。

    6.如何跟踪异常的传播路径?请通过 PrintExpressionStack.java示例掌握上述内容。

    public class PrintExceptionStack {
    public static void main( String args[] )
    {
       try {
          method1();
       }
       catch ( Exception e ) {
          System.err.println( e.getMessage() + "
    " );
          e.printStackTrace();
       }
    }
    
    public static void method1() throws Exception
    {
       method2();
    }
    
    public static void method2() throws Exception
    {
       method3();
    }
    
    public static void method3() throws Exception
    {
       throw new Exception( "Exception thrown in method3" );
    }
    }
    

      

    运行结果截图:

    当程序中出现异常时,JVM会依据方法调用顺序依次查找有关的错误处理程序。

    可使用printStackTrace getMessage方法了解异常发生的情况:

    printStackTrace:打印方法调用堆栈。

    每个Throwable类的对象都有一个getMessage方法,它返回一个字串,这个字串是在Exception构造函数中传入的,通常让这一字串包含特定异常的相关信息。

    7.依据对本讲多个示例程序的分析,请自行归纳总结出Java多层嵌套异常处理的基本流程。

    Java中异常分类:

    Throwable类有两个直接子类:

    Exception:出现的问题是可以被捕获的;

    Error:系统错误,通常由JVM处理。

    可捕获的异常又可以分为两类:

    1Check异常:直接派生自Exception的异常类,必须被捕获或再次声明抛出

    2Runtime异常:派生自RuntimeException的异常类。使用throw语句可以随时抛出这种异常对象:

       throw new ArithmeticException();

    try-catch-finally相互嵌套时,先处理最内层的try-catch-finally。当try抛出了与catch匹配的异常,则代码到相应的catch()中执行。如果catch也出现了异常,程序会检测finally中是否有异常,若有,则覆盖。如果只有try-finally,那么先执行finally,如果finally没有异常,则返回处理try中的异常,如果finally有异常,则覆盖try中的异常

     8.编写一个程序,此程序在运行时要求用户输入一个 整数,代表某门课的考试成绩,程序接着给出“不及格”、“及格”、“中”、“良”、“优”的结论。

    要求程序必须具备足够的健壮性,不管用户输入什 么样的内容,都不会崩溃        

    代码

    import java.util.Scanner;
    class judgeException extends Exception
    {
    	public judgeException(String s){
    	super(s);
    	}
    }
    class judgeException2 extends Exception
    {
    	public judgeException2(String s){
    	super(s);
    	}
    }
    public class Student {
    
    	public static void main(String[] args) {
    		boolean p=true;
    		while(p)  {
    		System.out.println("请输入一个整数:");
    		Scanner in=new Scanner(System.in);
    		  String s=in.next();
    		  try
    			{
    				for(int i=0;i<s.length();i++)
    				{
    				if((s.charAt(i)<48||s.charAt(i)>57))
    				{
    					throw new judgeException("输入的不是数字,请重新输入!");
    				}
    				}
    				try{
    					int m=Integer.parseInt(s);
    					if(m<0||m>100)
    					{
    					throw new judgeException2("输入的分数错误,请重新输入!");
    					 }
    					if(m<60)
    				   {
    					System.out.println("不及格");
    				    }
    					else if(m>=60&&m<=69)
    					{
    						System.out.println("及格");
    					}
    					else if(m>=70&&m<=79)
    					{
    						System.out.println("中");
    					}
    					else if(m>=80&&m<=89)
    					{
    						System.out.println("良");
    					}
    					else if (m>=90&&m<=100)
    					{
    						System.out.println("优");
    					}
    				   }
    					catch(judgeException2 e)
    					{
    						System.out.println(e.getMessage());
    					}
    				
    			}
    		catch (judgeException e)
    		{
    			System.out.println(e.getMessage());
    		}	
    		}
    	}
    }
    	
    

      

    截图:

  • 相关阅读:
    A Node Influence Based Label Propagation Algorithm for Community detection in networks 文章算法实现的疑问
    Fast Newman-FN算法以及模块度定义介绍
    Label Propagation Algorithm LPA 标签传播算法解析及matlab代码实现
    设计一个smartnic
    Intel GEN11 GPU
    Intel GEN9 GPU
    Shared Virtual Memory (SVM) Functions
    connect via ssh to virtualbox guest vm without knowing ip address
    smartnic
    技术精品翻译
  • 原文地址:https://www.cnblogs.com/1998lu/p/6101071.html
Copyright © 2011-2022 走看看