收藏 分销(赏)

java异常类基础入门.docx

上传人:二*** 文档编号:4576790 上传时间:2024-09-30 格式:DOCX 页数:12 大小:24.47KB 下载积分:5 金币
下载 相关 举报
java异常类基础入门.docx_第1页
第1页 / 共12页
本文档共12页,全文阅读请下载到手机保存,查看更方便
资源描述
1异常的基本概念异常:异常不是错误是程序中发生的不正常事件流它的根类为Execption ( Throwable ) Throwable 下面包括 Execption 和 error (错误); 异常分为:运行期异常和编译期异常; -旦发生了异常,异常代码以后的语句不会再执行,直接退出程序为了保证即使出现了异常,也不会让程序终止!(处理异常) try{可能会出现异常的代码 }catch(异常类型异常对象){ 捕获异常 }catch(异常类型异常对象){ 捕获异常 }…… finally(最终的执行语句,不管异常捕获与否都会去执行 )注意:不要随意将不相关的代码放到try块中,因为随时可能会中断执行。 捕获异常的时候尽量去捕获具体的异常信息 当有多个异常信息的时候必须把大的异常信息放在后面小的异常信息放在前面 public class SimpleDateFormatDemo ( public static void main(String[] args) (test(); ) public static void test()( 〃创建时间对象 Date date = new Date(); 〃创建不同格式的时间 DateFormat df = DateFormat.getlnstance(); DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EE”); DateFormat df2 = DateFormat.getDatelnstance(DateFormat.FULL,Locale.JAPAN);/俨生一个指定国家的日期,长度不同,显示日期的完整性也不同 DateFormat df3 = new SimpleDateFormat("yyyy 年 MM 月 dd 日 HH 时 mm 分 ss秒 EE",Locale.CHINA);DateFormat df4 = new SimpleDateFormat("yyyy-MM-dd"); System.out.println(*'java 自带的显示方式:"+date); System.out.println("§定义的模式显示: "+ dfl.format(date));(”按照 FULL 时间模式显示: H+df2.format(date));System.out.println("i$照区域为中国显示: "+df3.format(date));("按照 yyyy-MM-dd 显示: H+df4.format(date)); 泛型:泛型的本质是参数化类型 泛型可加在类,接口,方法上面 在方法上使用泛型时必须是引用数据类型或者是封装类型 泛型可以在类的外部指明方法和参数的类型Date.java package day09;import java.util.Date; public class DateDemo (public static Date getDate(){ return new Date(); } public static void main(String[] args) (Date d = getDate(); System.out.println(d);System, out. printin (d .geWateQ); System.out. println(d.geWayQ); System.out.printin(d.getHours()); System.out.println(d.; System.out.println(d.getYear()+1900): }) 12 SimpleDateFormat.javapackage day09; import java.text.DateFormat;import java.text.ParseException; import java.text.SimpleDateFormat;import java.util.Date; import java.util.Locale;public class SimpleDateFormatDemo ( public static void main(String[] args) throws ParseException (test(); ) public static void test() throws ParseException( 〃创建时间对象 Date date = new Date(); 〃创建不同格式的时间 DateFormat df = DateFormat.getlnstance(); DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss EE”); DateFormat df2 = DateFormat.getDatelnstance(DateFormat.FULL,Locale.JAPAN);//产生一个指定国家的日期,长度不同,显示日期的完整性也不同 DateFormat df3 = new SimpleDateFormat("yyyy 年 MM 月 dd H HH 时 mm分ss秒 EE",Locale.CHINA);DateFormat df4 = new SimpleDateFormat("yyyy-MM-dd"); System.out.println("java 自带的显示方式:"+date); System.out.println("§定义的模式显示: "+ dfl.format(date));(”按照 FULL 时间模式显示: H+df2.format(date));System.out.println(*按照区域为中国显示: ”+df3.format(date));("按照 yyyy-MM-dd 显示: H4-df4.format(date));/★ ★ *可将字符串转化为日期型*/ String str = "03-12-30 下午 2:24";String strr = ”2008-08-08 08:08:08 星期五”; Date datel = df.parse(str);//将字符串转化为 Date 对象Date date2 = df1 .parse(strr); System.out.println(datel);System.out.println(date2); )) 13 Calendar.javapackage day09; import java.text.SimpleDateFormat;import java.util.Calendar; import java.util.Date;import java.utiLGregorianCalendar; import java.util.Locale;import java.util.TimeZone; public class CalendarDemo ( public static void main(String[] args) (test(); ) public static void test()(Calendar now1 = Calendar.getlnstance(); Calendar now2 = new GregorianCalendar();Calendar now3 = new GregorianCalendar(2007,10,30); Calendar now4 = new GregorianCalendar(2007,10,30,15,55);Calendar now5 = new GregorianCalendar(2017,02,16,14,56,44); Calendar now6 = new GregorianCalendar(Locale.US); Calendar now7 = new GregorianCalendar(TimeZone.getTimeZone("GMT-8:00n));now2.setTime(new Date()); System.out.println(now2); SimpleDateFormat sdf = new SimpleDateFormat("yyyy 年 MM 月 dd H ”);System.out.println(sdf.format(now5.getTime())); System.out.println(now5.get(Calendar.YEAR));System.out.println(now1 .get(Calendar.MONTH)+1); System.out.println(now5.get(Calendar.DAY_OF_MONTH));System.out.println(now5.get(Calendar.HOUR)); System.out.println(now5.get(Calendar.M INUTE));System.out.println(now5.get(Calendar.SECOND)); System.out.println(now5.get(Calendar.AM_PM));System.out.println(now5.get(Calendar.DAY_OF_WEEK)); String week[] = {二”日”,”一”,”二三”,”四五”,“六}System.out.println(week[now5.get(Calendar.DAY_OF_WEEK)]); 14 Math数学类package day09; public class MathDemo ( public int maxValue(int x, int y)(int max = MathmQX(x, y); return max; ) public double duiS(double a){ double d = Math.Log(a); return d; } public static void main(String[] args) ( System.out.printIn(new MathDemo().max\/alue(50, 5)); System.out.printIn(new MathDemo().duiS(Math.E)); }} 15 Random.javapackage day09; import java.util.Random;public class RandomDemo ( public static void main(String[] args) { Random rand = new Random(); boolean flag = rand.nextBoolean(); System.out.printIn(flag); int number = rand.nextlnt(ll); System.out.printIn(number); )) 17泛型FXdemo.java package day09;public interface Fxdemo<T> ( void getFX(T t); String assume(T t);Point.java package day09;public class Ponit<T> {〃点 private T x; private T y;public T getX() ( return x; )public void setX(T x) ( this.x = x; )public T getY() ( return y; }public void setY(T y) ( this.y = y; }public boolean add(T tl){ return (boolean) tl; } public void test(Ponit<?> p){ System.out.println(p.getX()); System.out.println(p.getY()); }} FXD.java 测试package com.chinasofti.eec.test; import day09.Fxdemo;public class FXd implements Fxdemo<Integer>( ^Overridepublic void getFX(Integer t) ( System.out.printin(t); ) ^Overridepublic String assume(Integer t) { // TODO Auto-generated method stub return "helloworld"; public static void main(String[] args) ( Fxdemo<Integer> fx = new FXd(); fx.getFX(100); )} 输出100 Test.javapackage com.chinasofti.eec.test; import day09.Ponit;public class Test ( public static void main(String[] args) ( Ponit<Integer> p = new Ponit<Integer>(); p.setX(10);p.setY(10); Ponit〈String〉 pl = new Ponit<String>(); pl.setX(,,1010n);pl.setY(',10010H); Ponit<Boolean> p2 = new Ponit<Boolean>(); boolean flag = p2.add(false);System.out.println(pl.getX()+"======"+pl.getY()); System.out.println(flag);Ponit<Object> p3 = new Ponit<Object>(); p3.setX(250); p3.setY(250);Ponit<String> p4 = new Ponit<String>(); p4.setX("hello"); p4.setY("world");p3.test(p3); p4.test(p4);输出 1010======10010false 250250 hello world 不建议直接捕获Throwable因为它不仅仅包含异常还有error类所以一般使用Expection ; throw和throws的区别:throw用于方法体中,用来抛出一个实际的异常对象throws用于方法声明处,用来声明该方法可能发生的异 常类型,可以是多个异常类型,用来强制调用该方法时处理这些异常抽象方法也可以使用throws 编译期异常:文件流异常运行期异常:超出下标 Catch任意捕获先运行后catch ,如果没有catch直接从上往下 继承是单一的接口是多重的,实现完一个再去重写每个方法 继承一个类再实现一个接口先走 finally 再走 return Tran本身定义,自己定义自己Try catch抛出危险抛给java虚拟机(Exception ) 2 try catch 结构package day09; public class ExeceptionDemo ( public static void execptionTest()(int numl = 10; int num2 = 0;System ・ oi/t ・ printin ("====运彳亍前===="); try{System.out.println(numl/num2);//此时程序没有正常 运仃)catch(ArithmeticException e)( System. oi/t・println (”除数不能为0sb”); 〃此时程序没 有结束//e・ printStackTrace(); )System . out. println("====运行后====”); }public static void main(String[] args) ( execptionTestQ; }} 输出====运行前==== 除数不能为。sb====运彳了后==== 3 Exception 例子package day09; public class ExeceptionDemo ( public static void execptionTest()(int numl = 10; int num2 = 0;System ・ oi/t ・ println (”====运彳亍前====”); try(System, out. println(numl/num2);//此时程序没有正常 近仃}catch(ArithmeticException e)( System・oi/t・println (”除数不能为。sb”); 〃此时程序没 有结束 //e.printStackTrace();) System, out. println( "====运行后===="); ) public static void main(String[] args) (execptionTestQ; 输出====运行前==== ion: / by zero atdav09 ・ ExeceDtionDemo2 ・ execptionTest(ExeceptionDemo2 ・ java:9) at da,09・ExeceDtionDemo2・main(ExeceptionDemo2・ java:18) ====运行后====4数学异常 package day09;public class ExeceptionDemo3 { public static void execptionTest()(int numl = 10; int num2 = 0;System ・ ot/t ・ println (''====运彳亍前===="); try{System.out.println(numl/num2);//此时程序没有正常 X —Z —运仃 }catch(ArithmeticException e)(System. out. print In ("异常信息为:"+e); )finally (System.out.println("不管怎么样我都会去执行”); )System.out. println("====运行后====”); }public static void main(String[] args) ( execptionTestO; }} 5自定义方法public class MyExcption extends Exception { public MyExcption(String message) ( super(message); }} 6异常区域package day09; public class RunntimeExection ( public static int test(){int i = 10; int 1;try { System.out.println(j=i/0);System. out.println("异常区域”); } catch (Exception e) (System, out.print In ("捕获至I」的异常"); return i;)finally ( System.out.printin(j= i/10); System • out . print In (“最终执行“); } return i+100; }public static void main(String[] args) ( System.out.println(test()); )) 输出捕获到的异常 1最终执行 107异常输出 import java.util.InputMismatchException;import java.util.Scanner; public class RunntimeExection2 ( public static void test()(Scanner scan = new Scanner(System.in); System.out.println('请输入一个数');int str = 0; int num = 0;try { str = scan.nextlnt();num = str/O; }/*catch (Throwable e) (System.out.println(e); }*/catch (InputMismatchException e) (System.out.println(e); )catch (ArithmeticException e) (System.out.println(e); }catch(Exception e)(System.out.println(e); }("异常后执行"); ) public static void main(String[] args) (输出 请输入一个数1 java.lanR,ArithmeticException: / by zero 异常后执行8抛出异常 package day09;public class RunntimeExection3 ( public static void test(boolean isThrow) throws Exception{System. out ・ printin (”进入 test ()"); try {if(isThrow)( throw new Exception("test()抛出异常“); ) System.out.println("test()抛出异常后的 try 的内容 ”);} catch (Exception e) ( System.out.printIn(e);throw e; )System. out .println("异常后的信息”); }public static void main(String[] args) throws Exception { test(true); )} 9 finallypackage day09; public class Test ( static int test()(int x =1; try {return x; )finally (System, out. printlnC'Ullll"); x = x+100; ) )public static void main(String[] args) ( System ・oi/t・ print In (Test ・ test ()); }} 10抛出区域package day09; public class ThrowTest ( private String id = “123”; private double banlace;public ThrowTest(String id, double banlace) ( this.id = id; this.banlace = banlace; ) public String getld() {return id; )public void setId(String id) ( this.id = id; ) public double getBanlace() (return banlace; }public void setBanlace(double banlace) ( this.banlace = banlace; } public void deposit(double value) ( if(value>banlace){throw new Exception(); }) catch (Exception e) ( System. out. print In (H 余额不足 110"); return;banlace = banlace -value; System.out.printIn(banlace); }public static void main(String[] args) ( ThrowTest t = new ThrowTest("110", 5000); t.deposit(8000); )) 11本身定义package day09; public class Tran (static int avg(int nl^int n2) throws MyExcption( if(nl<0||n2<0)( throw new MyExcption("不能是负数!"); }else if(nl>100||n2>100){throw new MyExcption(”数值过大!"); } return (nl+n2)/2; ) public static void main(String[] args) ( int av = wg(50,50);System.out.printin(av); ) catch (MyExcption e) (// TODO Auto-generated catch block e, printStackTrace(); } }} Date package day09;import java.text.DateFormat; import java.text.SimpleDateFormat;import java.util.Date; import java.util.Locale;
展开阅读全文

开通  VIP会员、SVIP会员  优惠大
下载10份以上建议开通VIP会员
下载20份以上建议开通SVIP会员


开通VIP      成为共赢上传

当前位置:首页 > 通信科技 > 开发语言

移动网页_全站_页脚广告1

关于我们      便捷服务       自信AI       AI导航        抽奖活动

©2010-2026 宁波自信网络信息技术有限公司  版权所有

客服电话:0574-28810668  投诉电话:18658249818

gongan.png浙公网安备33021202000488号   

icp.png浙ICP备2021020529号-1  |  浙B2-20240490  

关注我们 :微信公众号    抖音    微博    LOFTER 

客服