java-Chapter 8 exception handling

Purpose:

      1. Familiar with exception handling mechanism.

      2. Master the capture methods of common exceptions.

Experiment content:

        1. Program the exception handling with a divisor of 0.

        2. Programming to realize the exception handling of input errors.

        3. Programming to realize the exception handling of illegal parameters.

Experimental steps:

1. Write a class ExceptionTest, use the try-catch-finally statement structure to achieve in the main method:

1) In the try statement block, write the division operation of two numbers, and the two operands of the division require user input when the program is running;

2) In the catch statement block, catch the exception generated by dividing by 0 and output the exception information;

3) In the finally statement block, output a statement at will, such as:

System. out .println( " Execute finally statement block. " );

Tip: Catch ArithmeticException .

Source code:

 

import java.util.Scanner;

 

public class ExceptionTest {

    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        System. out .println( " Please enter the dividend :\n" );

        int op1 = input.nextInt();     

        System. out .println( " Please enter the divisor: \n" );

        int op2 = input.nextInt();      

        int result = 0;

        try {

            result = op1 / op2;

        } catch (ArithmeticException e) {

            e.printStackTrace ();

        } finally {

            System. out .println( " Run complete " );

        }

        System.out.println(result);

    }

}

Screenshot of running result:

 

 

2. Write an application program that requires inputting the radius of a double circle from the keyboard, calculating and outputting its area. Test what results will be produced when the input data is not double data (such as the string "abc") and how to deal with it.

Tip: Catch InputMismatchException .

Source code:

import java.util.InputMismatchException;

import java.util.Scanner;

 

public class Circle {

    public static void main(String[] args){

        Scanner input = new Scanner(System.in);

        System. out .println( " Please enter the radius of the circle: " );

        double r = input.nextDouble();

        double s = 0;

        try {

            s = r*r*3.14;

        } catch (InputMismatchException e) {

            e.printStackTrace ();

        } finally {

            System. out .println( " Run complete " );

        }

        System. out .println( " The area of ​​the circle is: " +s);

    }

   

}

 

Screenshot of running result:

3. To design the class Person , it is required to input the ID number from the keyboard and set the value for the attribute id of the class. When the length of the input ID number is 18, assign the value to id. When the length of the value is not 18, an IllegalArgumentException is thrown. Then catch and handle the exception, write a program to achieve the above functions.

Tips: IllegalArgumentException is a user-defined exception, which cannot be automatically thrown by the system. It must be implemented through the throws statement. You can refer to the following code:

Source code:

import java.util.InputMismatchException;
import java.util.Scanner;


class person {
   
private String id;
   
public String getId(){
       
return id;
    }
   
public void setId(String id) throws IllegalArgumentException
   
{
       
if(id.length() != 18)
        {
           
throw(new IllegalArgumentException());
        }
       
this.id = id;
    }
}



public class Sy8_3 {
   
public static void main ( String [] args){
       
person p1 = new person();
       
Scanner input = new Scanner( System . in );
       
System . out .println( " Please enter ID Number: " );
       
try {
           
p1 .setId( input .next());
           
System . Out .println( " The ID you entered is :" + p1.getId());
        }
catch ( IllegalArgumentException e) {
           
System . out .println( " input error " );
        }
    }
}

 

Screenshot of running result:

   

Experiment summary

  1. Exceptions refer to various unexpected conditions, such as: file not found, network connection failure, illegal parameters, etc. An exception is an event that occurs during the running of the program and interferes with the normal instruction flow. Java describes a variety of different exceptions through many subclasses of the Throwable class in the API. Therefore, Java exceptions are all objects, instances of Throwable subclasses that describe error conditions that appear in a piece of code. When the condition is generated, the error will raise an exception.
  2. We can catch exceptions through the try and cat keywords, where catch can be used multiple times to capture multiple exceptions, as shown in the following figure:

  1. In the third step, you can use the throws keyword to throw an exception. Add the throws keyword and the thrown exception to the end of the method name, as shown in the following figure:

  1. We can throw multiple exceptions through the throws keyword, separated by commas after the thrown exception name, the following code throws RemoteException and InsufficientFundsException, as shown in the following figure:

  1. There is also a finally keyword in exception handling. The code in finally is always executed no matter whether there is an exception or not. It should be noted that finally is not necessary, as shown in the following figure

  1.  

Summary

Develop good programming habits and don’t swallow up errors (that is, if you catch the exception and do not deal with it accordingly, this approach is equivalent to hiding the error, but in fact the error still exists), also Don't throw mistakes out easily. If you can handle it, you must deal with it, and if you can't, you must throw it out. There are two methods of throwing out. One is to use throws to throw the exception out when the method is declared after knowing the type of the exception. The other is to throw it out manually. Using "throw+exception object" you are equivalent to throwing the exception object. Go out, and write the exception to be thrown in the method declaration.

Guess you like

Origin blog.csdn.net/qq_45176548/article/details/112342204