Chapter 7 Abnormalities

1. Write code that can generate ArrayIndexOutOfBoundsException, catch it, and output exception information on the console
package com.bdqn.demo;

public class ArrayExceotion {
    static int num[]=new int[3];//Array
     public static void main(String[] args) {
     try {//capture
    	 num[3]=4;
     }catch(ArrayIndexOutOfBoundsException e) {//Exception code block
    	 System.err.println("Array out of bounds!!!");
   	      e.printStackTrace ();
     }finally {
    	 System.out.println("Thank you for using!");
     }
     }
}

2. Modify the previous question, use log4j to record the log, and record the abnormal information generated in the jbit.log file

package com.bdqn.demo;

import org.apache.log4j.Logger;

public class ArrayExceotion {
	static Logger log=Logger.getLogger(ArrayExceotion.class);//Add log
	 static int num[]=new int[3];//Number array
     public static void main(String[] args) {
     try {//capture
    	 num[3]=4;
     }catch(ArrayIndexOutOfBoundsException e) {
    	 System.err.println("Array out of bounds!!!");
   	     
   	      log.error( e.getMessage());//Call log
     }finally {
    	 System.out.println("Thank you for using!");
     }
     }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325956956&siteId=291194637