异常处理
1 package com.unit12.test; 2 3 public class test1 { 4 5 public static void main(String[] args) { 6 int[] arry= {12,22,43,33,134,35,0,78,67,88,8}; 7 8 for(int x:arry) { 9 try {//可能会出现异常的代码 10 11 int y=100/x; 12 System.out.println("100/"+x+"结果是:"+y); 13 14 }catch (Exception e) {//当出现异常时执行的代码 15 16 System.out.println("出现异常"); 17 e.printStackTrace(); 18 19 }finally {//无论是否有异常,都会执行的代码 20 21 System.out.println("本次循环结束!"); 22 } 23 } 24 25 } 26 27 }
1 package com.unit12.test; 2 3 public class test2 { 4 5 //声明抛出异常,将异常交给方法的调用者去处理 6 public static void function1(int i) throws Exception{ 7 int y=100/i; 8 System.out.println("100/"+i+"结果是:"+y); 9 } 10 11 public static void main(String[] args) { 12 int[] arry= {12,22,43,33,134,35,0,78,67,88,8}; 13 14 for(int x:arry) { 15 try { 16 function1(x); 17 }catch (Exception e){ 18 e.printStackTrace(); 19 } 20 } 21 } 22 }
1 package com.unit12.test; 2 3 import java.util.Scanner; 4 5 public class test3 { 6 7 public static void main(String[] args) { 8 Scanner s=new Scanner(System.in); 9 System.out.println("请输入密码:"); 10 String pwd=s.next(); 11 12 if(pwd.length()==6) { 13 System.out.println("密码输入正确!"); 14 }else { 15 System.out.println("密码输入错误,长度必须是6位!"); 16 17 try { 18 throw new Exception("密码长度必须为6位!"); //自定义异常 19 } catch (Exception e) { 20 e.printStackTrace(); 21 } 22 } 23 24 } 25 26 }
posted on 2020-06-22 21:49 cherry_ning 阅读(68) 评论(0) 收藏 举报
浙公网安备 33010602011771号