zoukankan      html  css  js  c++  java
  • 异常处理---动手动脑及课后作业

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

    源码:

    import javax.swing.*;
    
    class AboutException {
       public static void main(String[] a) 
       {
          int i=1, j=0, k;
          k=i/j;
    
    
    	try
    	{
    		
    		k = i/j;    // Causes division-by-zero exception
    		//throw new Exception("Hello.Exception!");
    	}
    	
    	catch ( ArithmeticException e)
    	{
    		System.out.println("被0除.  "+ e.getMessage());
    	}
    	
    	catch (Exception e)
    	{
    		if (e instanceof ArithmeticException)
    			System.out.println("被0除");
    		else
    		{  
    			System.out.println(e.getMessage());
    			
    		}
    	}
    
    	
    	finally
         {
         		JOptionPane.showConfirmDialog(null,"OK");
         }
    		
      }
    }
    

      运行结果:

    注释掉第一个 k = i / j;

    知识:

    1.Try{ //可能发生运行错误的代码; } catch(异常类型 异常对象引用){ //用于处理异常的代码 } finally{ //用于“善后” 的代码 }

    2.使用Java异常处理机制

    把可能会发生错误的代码放进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"); 
                	}
     
                throw new ArithmeticException(); 
            } 
            catch(ArithmeticException e) { 
                System.out.println("发生ArithmeticException"); 
            } 
            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:当有多个嵌套的try…catch…finally时,要特别注意finally的执行时机。 请先阅读 EmbedFinally.java示例,再运行它,观察其输出并进行总结。 特别注意: 当有多层嵌套的finally时,异常在不同的层次抛出 ,在不同的位置抛出,可能会导致不同的finally语句块执行顺序。

    源代码:

    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");
            
    		}
        
    	}
    
    }
    

      运行结果:

    经过多次修改result = 100 / 0;的位置,可以得知将会跳过剩下的所有直到遇到第一个catch处理错误。继续运行剩下的。

    动手动脑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");
            
    		}
        
    	}
    
    
    }
    

      运行结果:

    System.exit(0);可以结束一切但是不可以阻止catch异常。

    课后作业:编写一个程序,此程序在运行时要求用户输入一个 整数,代表某门课的考试成绩,程序接着给出“不及格”、“及格”、“中”、“良”、“优”的结论。 要求程序必须具备足够的健壮性,不管用户输入什 么样的内容,都不会崩溃。

    源代码:

    package T9;
    
    import java.util.Scanner;
    
    class MyException extends Exception//输入异常
    {
    	public MyException()
    	{
    		
    	}
    	public MyException(String msg)
    	{
    		super(msg);
    	}
    }
    
    public class Score {
    
    	public static void main(String[] args) {
    		Scanner s = new Scanner(System.in);
    		String str = null;
    		double score = 0;
    		boolean flag = false;//判断输入格式正确
    		
    		System.out.print("请输入成绩(0-100):");
    		while(!flag)
    		{
    			try{
    				str = s.next();
    				for(int i = 0;i < str.length();i++)//判断输入的是不是double
    				{
    					if(str.length() == 1 && str.charAt(i) == '.')
    						throw new MyException("数字格式异常!");
    					if((str.charAt(i) >= '0' && str.charAt(i) <= '9') || str.charAt(i) == '.')
    						;
    					else
    						throw new MyException("数字格式异常!");
    					if(i == str.length() - 1)
    					{
    						score = Double.parseDouble(str);
    						if(score > 100.0 || score < 0.0)
    							throw new MyException("数字超出范围!");
    						else
    							flag = true;
    					}
    				}
    			}
    			catch(MyException e)//异常处理
    			{
    				System.out.print(e.getMessage());
    				System.out.print("请重新输入:");
    			}
    		}
    		
    		if(score >= 90)
    			System.out.println("优!");
    		else if(score >= 80)
    			System.out.println("良!");
    		else if(score >= 70)
    			System.out.println("中!");
    		else if(score >= 60)
    			System.out.println("及格!");
    		else
    			System.out.println("不及格!");
    	}
    
    }
    

      

      运行结果:

  • 相关阅读:
    实验十四 团队项目评审&个人学习总结
    实验四 附加实验项目互评
    201671010401 包稚潼+《英文文本统计分析》结队项目报告
    201671010401包稚潼 实验二 词频统计软件项目报告
    201671010401包稚潼 实验三作业互评与改进
    阅读《构建之法》提出的相关问题
    201671010404+陈润菊 实验十四 团队项目评审课程&学习总结
    201671010404+陈润菊 实验四 附加作业-项目互评
    201671010404+陈润菊 实验四《英文文本统计分析》结对项目报告
    201671010404+陈润菊 实验二软件工程项目
  • 原文地址:https://www.cnblogs.com/fylove/p/6102958.html
Copyright © 2011-2022 走看看