2023/7/07
今天完成了一些练习,从而对异常的抛出与处理有更好的理解
package 实践与练习; public class chu { public static void main(String[] args) { try { c(3,0); } catch(ArithmeticException e) { e.printStackTrace(); } } public static void c(int a,int b)throws ArithmeticException//只有都是整型才会抛出该种异常 { System.out.println(a/b); } }
package 实践与练习; import java.util.Scanner; class InException extends Exception { InException(String a) { super(a); } } public class input { public static void main(String[] args) { Scanner sc=new Scanner(System.in); String name=sc.next(); double age=sc.nextDouble(); try { a(age); }catch(InException e) { e.printStackTrace(); } } static void a(double a)throws InException//年龄不为整数就抛出异常 { if(a%1!=0) throw new InException("请输入正确的年龄"); } }
package 实践与练习; public class leixing { public static void main(String[] args) { int a; try { a=Integer.parseInt("nima");//数据类型转换异常 } catch(Exception e) { e.printStackTrace(); } finally { System.out.println("haohaohao"); } } }
package 实践与练习; class CException extends Exception { CException(String a) { super(a); } } public class Number { public static void main(String[] args) { try { int c=count(12315,57876876); System.out.println(c); } catch(Exception e) { e.printStackTrace(); } } public static int count(int a,int b)throws CException { if(a*b<0)//结果超过Int的界限就会变成负数 { throw new CException("结果超界了"); } else return a*b; } }
package 实践与练习; class DException extends Exception { DException(String a) { super(a); } } public class xunhuan { public static void main(String[]args) { for(int i=0;i<=9;i++) { try { System.out.println(i); if(i==2) { throw new DException("这里继续"); } }catch(DException e){ e.printStackTrace(); } } /* * 上面为抛出但是不中断循环 * 下面为抛出并且会中断循环 */ try { for(int i=0;i<=9;i++) { if(i==2) throw new DException("这里中断");//在try中for中抛出自定义异常就一定会结束 System.out.println(i); } } catch(DException e) { e.printStackTrace(); } } }
package 实践与练习; public class yuejie { public static void main(String[] args) { String b="666"; int[] a=new int[3]; try { for(int i=0;i<=3;i++) { //a[i]=0;数组索引越界异常 //System.out.println(b.charAt(i));字符串索引越界异常 } } catch(Exception e) { e.printStackTrace(); } } }
package 实践与练习; class YException extends Exception { YException (String a) { super(a); } } public class yueshu { public static void main(String[] args) { try { c(32,64); c(54,-18); } catch(YException e) { System.out.println(e); } } public static void c(int a,int b)throws YException { if(a<0||b<0)//操作数有负数就抛出异常 throw new YException("请输入正数"); else//辗转相除法最大公约数 { if(b>a) { int d=a; a=b; b=d; } int d=a%b; while(d!=0) { a=b; b=d; d=a%b; } System.out.println(b); } } }