Java _SSD3_Experiment 6 "Exception Handling"

  • Purpose
  1. Write a try-catch block to handle exceptions

 

  • Experiment content

1. [NumberFormatException] Write a program that prompts the user to enter two integers, and then displays their sum. Prompt the user to re-enter when the user makes a mistake.

 

    1. Operation results and analysis

 Test data one (correct input):

Test data two (input floating point number):

Test data three (input letters):

It can be seen from the above test results that the program fully meets the experimental requirements,

 

1 . 2 experience

   If you encounter an error type in the future, you must first understand what type it is, and it is best to go directly to the official website. For example, the error type NumberFormatException here is a type conversion error . Then there is another point, it will throw itself, as long as it catches it.

1.3 The source code is as follows



import java.util.Scanner;

/*.【NumberFormatException异常】编写一个程序,提示用户输入两个整数,然后显示它们的和。用户输入错误时提示用户重新输入。
不要自建类

s
 */
public class Program1 {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);
        System.out.println("请输入两个整数:");
        boolean flag = true;
        do{
         try {
             String a = input.next();
             String b = input.next();
             System.out.println(a+"+"+b+"="+(Integer.valueOf(a)+Integer.valueOf(b)));
             flag = false;         //只要在某一步捕获到错误就退出
         }
          catch (NumberFormatException ex){
              System.out.println("对不起!您的输入有误!\n请重新输入两个整数:");
          }
        }while (flag);

    }
}

2. (P419, 12.3) [ArrayIndexOutOfBoundsException] Write a program to create an array of 100 randomly selected integers; prompt the user to enter the array index, and then display the value of the element, if the specified index is out of range, a message is displayed out of bounds.

2.1 Operation results and analysis

Test data one (input correct):

Test data two (input wrong data):

It can be seen from the above test results that the program fully meets the experimental requirements.

 

2.2 Experience

  In order to achieve experimental purposes, you can also throw directly in the try statement block yourself. All in all, the exception handling mechanism is very beautiful.

 

2.3 The source code is as follows



import java.util.Scanner;






public class Program2 {
    public static void main(String[] args) {
        int[] random = new int[100];
        Scanner input = new Scanner(System.in);
        for(int i=0;i<100;i++)
            random[i] = (int)(Math.random() * 100000);

        boolean flag = true;
        System.out.print("请输入数组下标(0-99):");
       do{
           try{
               int index = input.nextInt();
               if(index < 0 || index >99)
                   throw new ArrayIndexOutOfBoundsException("out of bounds");
               System.out.println(random[index]);
               flag = false;
           }
           catch (ArrayIndexOutOfBoundsException ex){
               System.out.print("out of bounds!请重新输入:");
           }
       }while (flag);

    }

}

3. Please convert the content shown in the figure below into runnable code, try to throw different types of exceptions, and understand the process of finding exception handlers and the process of code execution 

3.1 Operation results and analysis

Check one:

 

 

 

Check two:

Inspection three:

Inspection four:

 

 

3.2 Experience

  How to use the program to experience the exception handling mechanism, the original idea is very clear. But I didn't expect that due to the large amount of code, my thoughts would be messed up, and I suddenly became annoyed. I think this is the reason why Java developers tend to be bald, hh. Fortunately, I compiled a super small program to check the operation of the exception handling mechanism under various conditions. The heart is still happy, through this program can experience the basic mechanism of exception handling at any time.

Then several problems were discovered: If an exception is thrown in the function, and all cacth statements cannot be caught, an error will be reported; if a required exception is thrown in a method, the method and all previous calls of the method Level methods need to declare the exception.

 

3.3 The source code is as follows

package Lab6;  
  
import java.io.IOException;  
import java.util.Scanner;  
  
/*请将393页图12-3所示的内容转换成可运行的代码,尝试抛出不同类型的异常,理解寻找异常处理器的过程及代码执行的流程。*/  
public class Program3 {  
    public static void method1(int a){//整数除以0异常  
        try {  
            System.out.println("方法一中调用方法二时的前面一条语句");  
            if(a == 1){  
                System.out.println("方法一中抛出ArithmeticException");  
                throw new ArithmeticException("1");  
            }  
            method2(a);  
            System.out.println("方法一中调用了方法二后的语句");  
        }  
        catch (NullPointerException ex){  
            System.out.println("方法一捕捉到方法三中的NullPointerException");  
        }  
        System.out.println("方法一try catch 块结束后的语句");  
    }  
  
    public static void method2(int a) //数组越界  
    {  
        try{  
  
            if(a == 2){  
                System.out.println("方法二中抛出IndexOutOfBoundsException");  
                throw new IndexOutOfBoundsException("2");  
            }  
            System.out.println("方法二中调用方法三时的前面一条语句");  
            method3(a);  
            System.out.println("方法二中调用方法三的后面一条语句");  
        }catch (NullPointerException ex){  
            System.out.println("方法二中捕捉到方法三中的NullPointerException");  
        }  
        System.out.println("方法二try catch 块结束后的语句");  
  
    }  
    public static void method3(int a) {//空指针异常 and IllegalArgumentException  
        try {  
            if(a == 3){  
                System.out.println("方法三中抛出NullPointerException");  
                throw new NullPointerException("3");  
            }  
            if(a == 4)  
            {  
                System.out.println("方法三中抛出ClassNotFoundException");  
                //throw new ClassNotFoundException("4");  
                Object o = new Object();  
                String s = (String)o;  
            }  
        }catch (IllegalArgumentException ex){  
            System.out.println("方法三中捕捉到IllegalArgumentException");  
        }  
        System.out.println("方法三try catch 块结束后的语句");  
  
    }  
  
    public static void main(String[] args) {  
        Scanner input = new Scanner(System.in);  
  
        System.out.println("1.抛出方法一中的异常!(只有主函数可以捕捉)");  
        System.out.println("2.抛出方法二中的异常!(只有主函数可以捕捉)");  
        System.out.println("3.抛出方法三中的异常!(方法二和主函数可以捕捉)");  
        System.out.println("4.抛出方法三中的异常!(没有任何的方法可以捕捉)");  
        System.out.print("输入你想检验的操作前面的代号:");  
        int a = input.nextInt();  
        System.out.println("下面输出程序将执行的语句:");  
        System.out.println();  
        try {  
            System.out.println("主函数中方法一前面的语句");  
            method1(a);  
            System.out.println("主函数中方法一后面的语句");  
        }  
  
        catch (NullPointerException ex){  
            System.out.println("主函数中捕捉到方法三中的NullPointerException");  
        }catch (IndexOutOfBoundsException ex){  
            System.out.println("主函数中捕捉到方法二中的IndexOutOfBoundsException");  
        }  
        catch (ArithmeticException ex){  
            System.out.println("主函数中捕捉到方法一中的ArithmeticException");  
        }  
  
        finally {  
            System.out.println("主函数中的finally子句");  
        }  
  
        System.out.println("主函数try catch 块结束后的语句");  
  
    }  
}  

 

Guess you like

Origin blog.csdn.net/qq_45768060/article/details/106337429