2018-07-24 14:42:24
第一种:
第二种:
第三种:
执行
try--catch--finally--return(执行return 退出方法)
代码示例:
输入数字,输出对应课程
1.如果输入的不是数字,抛出异常
2.如果输入的是数字,但数字没有对应的课程,抛出异常
throw new Exception();
catch 捕获对应异常,处理 或者 在方法声明的时候抛出异常类型,由方法的调用者处理异常
1 package day09.com.neusoft.test; 2 3 import java.util.Scanner; 4 5 public class InOutException { 6 7 public static void main(String[] args) { 8 // TODO Auto-generated method stub 9 Scanner input = new Scanner(System.in); 10 11 System.out.println("请输入课程代号(1~3):"); 12 13 try { 14 15 int a = input.nextInt(); 16 17 if(a==1||a==2||a==3){ 18 switch(a) { 19 case 1: 20 System.out.println("JAVA编程"); 21 break; 22 case 2: 23 System.out.println("ORACLE数据库"); 24 break; 25 case 3: 26 System.out.println("C语言编程"); 27 break; 28 } 29 }else { 30 31 throw new Exception(); 32 } 33 }catch(Exception e) { 34 System.out.println("您的输入不合法!"); 35 } 36 System.out.println("欢迎提出建议!"); 37 38 } 39 40 }
log4j
步骤:
1.在项目的目录下新建 lib文件夹
2.log4j.jar--->lib
3.build path 构建路径
4.log4j.properties--->项目目录或(包目录)下
1 package day09.com.neusoft.test; 2 3 import org.apache.log4j.Logger; 4 5 /** 6 * 数组下标越界异常 7 * @author ljj 8 * 9 */ 10 public class ArrayExcaption { 11 private static Logger jbit = Logger.getLogger(ArrayExcaption.class.getName()); 12 public static void main(String[] args) { 13 14 int[] arr = new int[] {1,2,3,4,5}; 15 jbit.debug("数组的第一个值:"+arr[0]); 16 try { 17 //遍历数组 18 for(int i=0;i<=arr.length;i++){ 19 System.out.println(arr[i]); 20 } 21 } catch (ArrayIndexOutOfBoundsException e) { 22 jbit.error("数组下标越界!",e); 23 //System.out.println("数组下标越界!"+e.getMessage()); 24 }catch(Exception e) { 25 //e.getStackTrace(); 26 jbit.error(e.getMessage()); 27 }finally { 28 System.out.println("欢迎使用本程序!"); 29 } 30 31 } 32 33 }
jbit是文件名
1 package day09.com.neusoft.test; 2 3 import java.util.InputMismatchException; 4 import java.util.Scanner; 5 6 import org.apache.log4j.Logger; 7 8 /** 9 * 除法运算 10 * @author ljj 11 * 12 */ 13 public class InputaErrorException { 14 private static Logger logger = Logger.getLogger(InputaErrorException.class.getName()); 15 public static void main(String[] args) { 16 // TODO Auto-generated method stub 17 Scanner input = new Scanner(System.in); 18 19 // 20 try { 21 System.out.println("请输入被除数:"); 22 int a = input.nextInt(); 23 System.out.println("请输入除数:"); 24 int b = input.nextInt(); 25 System.out.println("a/b="+a/b); 26 logger.info("a/b="+a/b); 27 }catch(InputMismatchException ie) { 28 logger.error(ie.getMessage()); 29 30 }catch(ArithmeticException ae) { 31 logger.warn(ae.getMessage()); 32 } 33 34 } 35 36 }
try{
}finally{
}
可以这样用