今日目标
1、能够熟练使用Date类和SimpleDateFormat类中的常见方法
2、能够了解Jdk1.8新提供的日历类的使用
3、能够理解什么是异常
知识点
- 时间日期类
- JDK8时间类
- 异常
1.时间日期类
1.1 时间概述(视频01) (5‘’)
- 北京时间需要在世界标准时间加上8小时
- 计算机中时间原点(UNIX操作系统,C语言的诞生日)

1970年1月1日 00:00:00
3.时间换算单位
1秒 = 1000毫秒
1.2 时间日期类-Date构造方法(视频02) (7‘’)
-
什么是Date类
Date 代表了一个特定的时间,精确到毫秒
2.Date类构造方法
| 方法名 | 说明 |
|---|---|
| public Date() | 创建 Date对象,默认存储当前时间,单位毫秒 |
| public Date(long date) | 创建 Date对象,并将其初始化为表示从标准基准时间起指定的毫秒数 |
示例代码
package com.itheima.mydate;
import java.util.Date;
public class DateDemo1 {
public static void main(String[] args) {
//public Date() 创建一个Date对象,表示默认时间
//public Date(long date) 创建一个Date对象,表示指定时间
//那么这个时间就表示电脑中的当前时间。
Date date1 = new Date();
System.out.println(date1);
//从计算机的时间原点开始,过了指定毫秒的那个时间。
Date date2 = new Date(0L);
System.out.println(date2);//Thu Jan 01 08:00:00 CST 1970
//从时间原点开始,过了0毫秒。
//因为我们是在中国,我们是在东八区需要+8小时。
//1970年1月1日 上午的10点
Date date3 = new Date(2 * 3600L * 1000);
System.out.println(date3);
}
}
1.3 时间日期类-Date成员方法(应用)(视频03) (4‘’)
-
常用方法
方法名 说明 public long getTime() 获取从1970年1月1日 00:00:00到该日期对象代表时间的毫秒值 public void setTime(long time) 设置时间,给的是毫秒值 -
示例代码
package com.itheima.mydate; import java.text.SimpleDateFormat; import java.util.Date; public class DateDemo2 { public static void main(String[] args) { //public long getTime() 获取时间对象的毫秒值 //public void setTime(long time) 设置时间,传递毫秒值 //method1(); //method2(); } private static void method2() { Date date1 = new Date(); date1.setTime(0L); System.out.println(date1); } private static void method1() { //把当前时间封装成一个date对象 Date date1 = new Date(); //获取这个date对象的毫秒值 --- 获取当前时间的毫秒值 long time = date1.getTime(); System.out.println(time); long time2 = System.currentTimeMillis(); System.out.println(time2); } }
1.4 SimpleDateFormat类(应用)(视频04) (12‘’)
(共2点)
1.SimpleDateFormat类有什么作用?
SimpleDateFormat可以对Date对象,进行格式化和解析
2.如何使用?
1.常用的模式字母及应对关系如下:
HH:24小制,hh:12小时制

2.SimpleDateFormat类构造方法
| 方法名 | 说明 |
|---|---|
| public SimpleDateFormat() | 构造一个SimpleDateFormat,使用默认模式和日期格式 |
| public SimpleDateFormat(String pattern) | 构造一个SimpleDateFormat使用给定的模式 |
3.SimpleDateFormat类的常用方法
- 格式化(从Date到String)
public final String format(Date date):将日期格式化成日期/时间字符串
- 解析(从日期/时间字符串String到Date)
public Date parse(String source):从给定字符串的开始解析文本以生成日期
示例代码(公历日期标准格式为;2007年2月6日;或:2007-02-06)
//将Date转换成固定格式的字符串
public class DateDemo3 {
public static void main(String[] args) {
//当前时间的Date对象
Date date = new Date();
//创建了一个日期格式。
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String result1 = sdf.format(date);
System.out.println(result1);
}
}
//将固定格式的字符串转换成Date
public class DateDemo4 {
public static void main(String[] args) throws ParseException {
String s = "2048-01-01";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date = sdf.parse(s);
System.out.println(date);
}
}
自由练习-8分钟 - (parse&format方法)
1.5 时间日期类练习 (应用) (视频05)(9’’)
-
需求
秒杀开始时间是2020年11月11日 00:00:00,结束时间是2020年11月11日 00:10:00,用户小贾下单时间是2020年11月11日 00:03:47,用户小皮下单时间是2020年11月11日 00:10:11,判断用户有没有成功参与秒杀活动
-
实现步骤
- 判断下单时间是否在开始到结束的范围内
- 把字符串形式的时间变成毫秒值
-
代码实现
```java``
package com.itheima.mydate;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class DateDemo5 {
public static void main(String[] args) throws ParseException {
//开始时间:2020年11月11日 0:0:0
//结束时间:2020年11月11日 0:10:0
//小贾2020年11月11日 0:03:47
//小皮2020年11月11日 0:10:11
//1.判断两位同学的下单时间是否在范围之内就可以了。
//2.要把每一个时间都换算成毫秒值。
String start = "2020年11月11日 0:0:0";
String end = "2020年11月11日 0:10:0";
String jia = "2020年11月11日 0:03:47";
String pi = "2020年11月11日 0:10:11";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
long startTime = sdf.parse(start).getTime();
long endTime = sdf.parse(end).getTime();
long jiaTime = sdf.parse(jia).getTime();
long piTime = sdf.parse(pi).getTime();
if(jiaTime >= startTime && jiaTime <= endTime){
System.out.println("小贾同学参加上了秒杀活动");
}else{
System.out.println("小贾同学没有参加上秒杀活动");
}
System.out.println("------------------------");
if(piTime >= startTime && piTime <= endTime){
System.out.println("小皮同学参加上了秒杀活动");
}else{
System.out.println("小皮同学没有参加上秒杀活动");
}
}
}
小结
1北京时间需要在世界标准时间加上8小时
2 计算机中时间原点 1970年1月1日 00:00:00
3时间换算单位 1秒 = 1000毫秒
4.Date类
这个类是干什么的? 时间类、 Date 代表了一个特定的时间,精确到毫秒
如何创建时间对象? new Date()
常用方法: getTime()
-
SimpleDateFormat类
这个类是干什么的? 定义日期的格式,用于格式转换
如何创建时间对象? new SimpleDateFormat(“日期模式”)
常用方法:
format(Date date) 将Date转换成字符串
parse(String source) 将字符串转换成Date ```
2.JDK8时间日期类
2.1 JDK8时间类-初体验(视频6) (7’’)
需求
定义一个时间,String start = ""2020年11月11日 00:00:00;
将这个时间+1天,再按照原来的格式进行输出
```java
//jdk8以前的写法
private static void JDKMethod() throws ParseException {
//定义时间格式
String s = "2020年11月11日 00:00:00";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
//转换成Date
Date date = sdf.parse(s);
//将时间+1天
long time = date.getTime();
time = time + (1000 * 60 * 60 * 24);
Date newDate = new Date(time);
//转换成String
String result = sdf.format(newDate);
System.out.println(result);
}
//jdk8写法
private static void JDK8Method() {
//定义时间格式
String s = "2020年11月11日 00:00:00";
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
//转换成LocalDateTime
LocalDateTime localDateTime = LocalDateTime.parse(s, pattern);
//将时间+1天
LocalDateTime newLocalDateTime = localDateTime.plusDays(1);
//转换成String
String result = newLocalDateTime.format(pattern);
System.out.println(result);
}
2.2 JDK8时间类-获取时间对象 (应用) (视频7) (6’’)
1.jdk8中新增的时间类有哪些?
- LocalDate 表示日期(年月日)
- LocalTime 表示时间(时分秒)
- LocalDateTime 表示时间+ 日期 (年月日时分秒)(最常用)
2 如何创建LocalDateTime对象? (应用)
方法说明
| 方法名 | 说明 |
|---|---|
| public static LocalDateTime now() | 获取当前系统时间相当于new Date() |
| public static LocalDateTime of (年, 月 , 日, 时, 分, 秒) | 使用指定年月日和时分秒初始化一个LocalDateTime对象 new Date(1000L);指定一下时间 |
示例代码
package com.itheima.jdk8date;
import java.time.LocalDateTime;
public class JDK8DateDemo2 {
public static void main(String[] args) {
LocalDateTime now = LocalDateTime.now();
System.out.println(now);
LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 11, 11, 11);
System.out.println(localDateTime);
}
}
2.3 LocalDateTime获取方法 (了解)(视频8)(8’’)
-
方法说明
方法名 说明 public int getYear() 获取年 public int getMonthValue() 获取月份(1-12) public int getDayOfMonth() 获取月份中的第几天(1-31) public int getDayOfYear() 获取一年中的第几天(1-366) public DayOfWeek getDayOfWeek() 获取星期 public int getHour() 获取小时 public int getMinute() 获取分钟
| public int getSecond() | 获取秒 |
-
示例代码
package com.itheima.jdk8date; import java.time.DayOfWeek; import java.time.LocalDateTime; import java.time.Month; public class JDK8DateDemo3 { public static void main(String[] args) { LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 11, 11, 20); //public int getYear() 获取年 int year = localDateTime.getYear(); System.out.println("年为" +year); //public int getMonthValue() 获取月份(1-12) int month = localDateTime.getMonthValue(); System.out.println("月份为" + month); Month month1 = localDateTime.getMonth(); //System.out.println(month1); //public int getDayOfMonth() 获取月份中的第几天(1-31) int day = localDateTime.getDayOfMonth(); System.out.println("日期为" + day); //public int getDayOfYear() 获取一年中的第几天(1-366) int dayOfYear = localDateTime.getDayOfYear(); System.out.println("这是一年中的第" + dayOfYear + "天"); //public DayOfWeek getDayOfWeek()获取星期 DayOfWeek dayOfWeek = localDateTime.getDayOfWeek(); System.out.println("星期为" + dayOfWeek); //public int getMinute() 获取分钟 int minute = localDateTime.getMinute(); System.out.println("分钟为" + minute); //public int getHour() 获取小时 int hour = localDateTime.getHour(); System.out.println("小时为" + hour); } }
2.4 LocalDateTime转换方法 (了解)(视频9) (3’’)
方法说明
| 方法名 | 说明 |
|---|---|
| public LocalDate toLocalDate () | 转换成为一个LocalDate对象 |
| public LocalTime toLocalTime () | 转换成为一个LocalTime对象 |
示例代码
public class JDK8DateDemo4 {
public static void main(String[] args) {
LocalDateTime localDateTime = LocalDateTime.of(2020, 12, 12, 8, 10, 12);
//public LocalDate toLocalDate () 转换成为一个LocalDate对象
LocalDate localDate = localDateTime.toLocalDate();
System.out.println(localDate);
//public LocalTime toLocalTime () 转换成为一个LocalTime对象
LocalTime localTime = localDateTime.toLocalTime();
System.out.println(localTime);
}
}
2.5 JDK8时间类-格式化和解析 (应用)(视频10) (7’’)
方法说明
| 方法名 | 说明 |
|---|---|
| public String format (指定格式) | 把一个LocalDateTime格式化成为一个字符串 |
| public static LocalDateTime parse (准备解析的字符串, 解析格式) | 把一个日期字符串解析成为一个LocalDateTime对象 |
| public static DateTimeFormatter ofPattern(String pattern) | 使用指定的日期模板获取一个日期格式化器DateTimeFormatter对象 |
示例代码
package com.itheima.jdk8date;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
public class JDK8DateDemo5 {
public static void main(String[] args) {
//method1();
//method2();
}
//public static LocalDateTime parse (准备解析的字符串, 解析格式) 把一个日期字符串解析成为一个LocalDateTime对象
private static void method2() {
String s = "2020年11月12日 13:14:15";
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
LocalDateTime parse = LocalDateTime.parse(s, pattern);
System.out.println(parse);
}
//public String format (指定格式) 把一个LocalDateTime格式化成为一个字符串
private static void method1() {
LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 12, 13, 14, 15);
DateTimeFormatter pattern = DateTimeFormatter.ofPattern("yyyy年MM月dd日 HH:mm:ss");
String s = localDateTime.format(pattern);
System.out.println(s);
}
}
自由练习-8分钟
2.6 jdk8时间类-plus (了解)(视频11) (6‘’)
方法说明
| 方法名 | 说明 |
|---|---|
| public LocalDateTime plusYears (long years) | 添加或者减去年 |
| public LocalDateTime plusMonths(long months) | 添加或者减去月 |
| public LocalDateTime plusDays(long days) | 添加或者减去日 |
| public LocalDateTime plusHours(long hours) | 添加或者减去时 |
| public LocalDateTime plusMinutes(long minutes) | 添加或者减去分 |
| public LocalDateTime plusSeconds(long seconds) | 添加或者减去秒 |
| public LocalDateTime plusWeeks(long weeks) | 添加或者减去周 |
示例代码
/**
* JDK8 时间类添加或者减去时间的方法
*/
public class JDK8DateDemo6 {
public static void main(String[] args) {
//public LocalDateTime plusYears (long years) 添加或者减去年
LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15);
//LocalDateTime newLocalDateTime = localDateTime.plusYears(1);
//System.out.println(newLocalDateTime);
LocalDateTime newLocalDateTime = localDateTime.plusYears(-1);
System.out.println(newLocalDateTime);
}
}
2.7 jdk8时间类-minus (了解)(视频12)(3‘’)
方法说明
| 方法名 | 说明 |
|---|---|
| public LocalDateTime minusYears (long years) | 减去或者添加年 |
| public LocalDateTime minusMonths(long months) | 减去或者添加月 |
| public LocalDateTime minusDays(long days) | 减去或者添加日 |
| public LocalDateTime minusHours(long hours) | 减去或者添加时 |
| public LocalDateTime minusMinutes(long minutes) | 减去或者添加分 |
| public LocalDateTime minusSeconds(long seconds) | 减去或者添加秒 |
| public LocalDateTime minusWeeks(long weeks) | 减去或者添加周 |
示例代码
package com.itheima.jdk8date;
import java.time.LocalDateTime;
/**
* JDK8 时间类减少或者添加时间的方法
*/
public class JDK8DateDemo7 {
public static void main(String[] args) {
//public LocalDateTime minusYears (long years) 减去或者添加年
LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15);
//LocalDateTime newLocalDateTime = localDateTime.minusYears(1);
//System.out.println(newLocalDateTime);
LocalDateTime newLocalDateTime = localDateTime.minusYears(-1);
System.out.println(newLocalDateTime);
}
}
2.8 LocalDateTime修改方法 (了解)(视频13) (4‘’)
方法说明
| 方法名 | 说明 |
|---|---|
| public LocalDateTime withYear(int year) | 直接修改年 |
| public LocalDateTime withMonth(int month) | 直接修改月 |
| public LocalDateTime withDayOfMonth(int dayofmonth) | 直接修改日期(一个月中的第几天) |
| public LocalDateTime withDayOfYear(int dayOfYear) | 直接修改日期(一年中的第几天) |
| public LocalDateTime withHour(int hour) | 直接修改小时 |
| public LocalDateTime withMinute(int minute) | 直接修改分钟 |
| public LocalDateTime withSecond(int second) | 直接修改秒 |
示例代码
/**
* JDK8 时间类修改时间
*/
public class JDK8DateDemo8 {
public static void main(String[] args) {
//public LocalDateTime withYear(int year) 修改年
LocalDateTime localDateTime = LocalDateTime.of(2020, 11, 11, 13, 14, 15);
// LocalDateTime newLocalDateTime = localDateTime.withYear(2048);
// System.out.println(newLocalDateTime);
LocalDateTime newLocalDateTime = localDateTime.withMonth(20);
System.out.println(newLocalDateTime);
}
}
2.9 Period (了解)(视频14) (9‘’)
-
方法说明
方法名 说明 public static Period between(开始时间,结束时间) 计算两个“时间"的间隔 public int getYears() 获得这段时间的年数 public int getMonths() 获得此期间的总月数 public int getDays() 获得此期间的天数 public long toTotalMonths() 获取此期间的总月数 -
示例代码
计算两个时间的间隔
package com.itheima.jdk8date;
import java.time.LocalDate;
import java.time.Period;
public class JDK8DateDemo9 {
public static void main(String[] args) {
//public static Period between(开始时间,结束时间) 计算两个"时间"的间隔
LocalDate localDate1 = LocalDate.of(2020, 1, 1);
LocalDate localDate2 = LocalDate.of(2048, 12, 12);
Period period = Period.between(localDate1, localDate2);
System.out.println(period);//P28Y11M11D
//public int getYears() 获得这段时间的年数
System.out.println(period.getYears());//28
//public int getMonths() 获得此期间的月数
System.out.println(period.getMonths());//11
//public int getDays() 获得此期间的天数
System.out.println(period.getDays());//11
//public long toTotalMonths() 获取此期间的总月数
System.out.println(period.toTotalMonths());//347
}
}
2.10 Duration (了解)(视频14) (9‘’)
-
方法说明
方法名 说明 public static Duration between(开始时间,结束时间) 计算两个“时间"的间隔 public long toSeconds() 获得此时间间隔的秒 public int toMillis() 获得此时间间隔的毫秒 public int toNanos() 获得此时间间隔的纳秒 -
示例代码
计算两个时间的间隔
package com.itheima.jdk8date;
import java.time.Duration;
import java.time.LocalDateTime;
/**
* 计算两个时间的间隔
*/
public class JDK8DateDemo10 {
public static void main(String[] args) {
//public static Duration between(开始时间,结束时间) 计算两个“时间"的间隔
LocalDateTime localDateTime1 = LocalDateTime.of(2020, 1, 1, 13, 14, 15);
LocalDateTime localDateTime2 = LocalDateTime.of(2020, 1, 2, 11, 12, 13);
Duration duration = Duration.between(localDateTime1, localDateTime2);
System.out.println(duration);//PT21H57M58S
//public long toSeconds() 获得此时间间隔的秒
System.out.println(duration.toSeconds());//79078
//public int toMillis() 获得此时间间隔的毫秒
System.out.println(duration.toMillis());//79078000
//public int toNanos() 获得此时间间隔的纳秒
System.out.println(duration.toNanos());//79078000000000
//计算年龄
String birtthday="1995-01-01 00:00:00";
DateTimeFormatter dateTimeFormatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
LocalDateTime birthdayTime = LocalDateTime.parse(birtthday, dateTimeFormatter);
//计算活了多少天
Duration between = Duration.between( birthdayTime,LocalDateTime.now());
long days = between.toDays();
System.out.println(days);
//计算活了多少岁
Period period = Period.between(
birthdayTime.toLocalDate(),
LocalDateTime.now().toLocalDate());
System.out.println("活了"+period.getYears()+"岁,零"+period.getMonths()+"月,零"+period.getDays()+"天");
}
}
2.11 jdk8时间类-小结(视频15) (4‘’)
创建时间对象(now, of )
将日期类转换成字符串(format)
将字符串转换成日期类(parse)
获取时间对象中的年,月,日,时,分,秒 (get开头)
增加或减少时间的方法(plus开头,minus开头)
修改时间(with开头)
计算间隔(until方法)
这么多类、这么多方法,要疯
记不住啊
关键要会观察、会查询帮助文档
3.异常
3.1 异常的体系结构和分类(记忆)(视频16)(9’’)
1.什么是异常?
异常就是程序出现了不正常的情况(其实就是: 代码报错了)
**注意:**语法错误不算在异常体系中
2.异常的体系结构

//除RuntimeException之外的异常
public class ExceptionDemo1 {
public static void main(String[] args) {
// int [] arr = {1,2,3,4,5};
// System.out.println(arr[10]);//ArrayIndexOutOfBoundsException
// String s = null;
// System.out.println(s.equals("嘿嘿"));//NullPointerException
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
sdf.parse("2048-1月1日");//ParseException
}
}
3.编译时异常和运行时异常的区别(记忆)
-
编译时异常
- 都是Exception类及其子类
- 必须显式处理(手动处理),否则程序就会发生错误,无法通过编译
-
运行时异常
- 都是RuntimeException类及其子类
- 无需显式处理(手动处理),也可以和编译时异常一样处理
-
图示

3.2 JVM默认处理异常的方式(理解)(视频17)(4’’)
异常处理 : 并不是把异常解决掉,而是把发生异常的信息(什么地方出现了什么异常) 展示出来

1.如果程序出现了问题,我们没有做任何处理,最终JVM会做默认的处理,处理方式有如下两个步骤:
-
把异常的名称,错误原因及异常出现的位置等信息输出在了控制台
-
程序停止执行

package com.itheima.exce;
public class ExceptionDemo2 {
public static void main(String[] args){
//思考:控制台为什么会有这样的红色字体呢? 是谁打印的?
int [] arr = {1,2,3,4,5};
System.out.println(arr[10]);//当代码出现了异常,那么就在这里创建了一个异常对象.
//new ArrayIndexOutOfBoundsException();
//首先会看,程序中有没有自己处理异常的代码.
//如果没有,交给本方法的调用者处理.
//最终这个异常会交给虚拟机默认处理.
//JVM默认处理异常做了哪几件事情:
//1,将异常信息以红色字体展示在控制台上.
//2,停止程序运行. --- 哪里出现了异常,那么程序就在哪里停止,下面的代码不执行了.
System.out.println("嘿嘿嘿,我最帅");
}
}
3.3throws方式处理异常(应用)(视频18) (5’’)
1.定义格式
public void 方法() throws 异常类名 {
}
示例代码
package com.itheima.exce;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class ExceptionDemo6 {
public static void main(String[] args) throws ParseException {
method1(); //此时调用者也没有处理.还是会交给虚拟机处理.
method2(); //还是继续交给调用者处理.而main方法的调用者是虚拟机还是会采取虚拟机默认处理异常的方法.
}
//告诉调用者,你调用我,有可能会出现这样的异常哦.
//如果方法中没有出现异常,那么正常执行
//如果方法中真的出现了异常,其实也是将这个异常交给了调用者处理.
private static void method1() /*throws NullPointerException*/ {
int [] arr = null;
for (int i = 0; i < arr.length; i++) {//出现的空指针异常,还是由虚拟机创建出来的.
System.out.println(arr[i]);
}
}
//告诉调用者,你调用我,有可能会出现这样的异常哦.
//如果方法中没有出现异常,那么正常执行
//如果方法中真的出现了异常,其实也是将这个异常交给了调用者处理.
private static void method2() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
sdf.parse("2048-10月10日");
}
}
3.4 throws方式处理异常-注意事项(应用)(视频19) (2’’)
简单来说: 编译时的异常,必须声明由谁处理,最多让jvm来处理. 运行时异常可以不声明
package com.itheima.exce;
import java.text.ParseException;
import java.text.SimpleDateFormat;
public class ExceptionDemo6 {
public static void main(String[] args) throws ParseException {
method1(); //此时调用者也没有处理.还是会交给虚拟机处理.
method2(); //还是继续交给调用者处理.而main方法的调用者是虚拟机还是会采取虚拟机默认处理异常的方法.
}
//告诉调用者,你调用我,有可能会出现这样的异常哦.
//如果方法中没有出现异常,那么正常执行
//如果方法中真的出现了异常,其实也是将这个异常交给了调用者处理.
//如果声明的异常是一个运行时异常,那么声明的代码可以省略
private static void method1() /*throws NullPointerException*/ {
int [] arr = null;
for (int i = 0; i < arr.length; i++) {//出现的空指针异常,还是由虚拟机创建出来的.
System.out.println(arr[i]);
}
}
//告诉调用者,你调用我,有可能会出现这样的异常哦.
//如果方法中没有出现异常,那么正常执行
//如果方法中真的出现了异常,其实也是将这个异常交给了调用者处理.
//如果声明的异常是一个编译时异常,那么声明的代码必须要手动写出.
private static void method2() throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
sdf.parse("2048-10月10日");
}
}
3.5 throw抛出异常 (应用) (视频20) (10’’)
1.格式
throw new 异常();
2.注意
这个格式是在方法内的,表示当前代码手动抛出一个异常,下面的代码无法再执行了
3.抛出处理异常的意义
1.在方法中,当传递的参数有误时,没有继续运行的必要了,采取抛出处理,表示该方法结束
- 告诉调用者方法中出现了问题
4.throws和throw的区别
| throws (抛出现有异常) | throw (主动制造异常) |
|---|---|
| 用在方法声明后面,跟的是异常类名 | 用在方法体内,跟的是异常对象名 |
| 可以声明多个异常 | 只能有一个 |
示例代码
package com.itheima.exce;
public class ExceptionDemo7 {
public static void main(String[] args) {
System.out.println("家里有一个貌美如花的老婆");
System.out.println("还有一个当官的兄弟");
System.out.println("自己还有一个买卖");
System.out.println("这样的生活你要不要?");
throw new RuntimeException(); //当代码执行到这里,就创建一个异常对象
//该异常创建之后,暂时没有手动处理.抛给了调用者处理
//下面的代码不会再执行了.
//System.out.println("武大郎的标准生活");
}
}
package com.itheima.exce;
public class ExceptionDemo8 {
public static void main(String[] args) {
//int [] arr = {1,2,3,4,5};
int [] arr = null;
printArr(arr);//就会 接收到一个异常.
//我们还需要自己处理一下异常.
}
private static void printArr(int[] arr) {
if(arr == null){
//调用者知道成功打印了吗?
//System.out.println("参数不能为null");
throw new NullPointerException(); //当参数为null的时候
//手动创建了一个异常对象,抛给了调用者.
}else{
for (int i = 0; i < arr.length; i++) {
System.out.println(arr[i]);
}
}
}
}
3.6 try-catch自己处理异常(应用)(视频21) (5’’)
-
定义格式
try { 可能出现异常的代码; } catch(异常类名 变量名) { 异常的处理代码; }idea快捷键 ctrl + alt + t 自动生成try{}catch(){}代码
-
执行流程
- 程序从 try 里面的代码开始执行
- 出现异常,就会跳转到对应的 catch 里面去执行
- 执行完毕之后,程序还可以继续往下执行
-
示例代码
package com.itheima.exce; public class ExceptionDemo9 { public static void main(String[] args) { //好处:为了能让代码继续往下运行. int [] arr = null; try{ //有肯能发现异常的代码 printArr(arr); }catch (NullPointerException e){ //如果出现了这样的异常,那么我们进行的操作 System.out.println("参数不能为null"); } System.out.println("嘿嘿嘿,我最帅!!!"); } private static void printArr(int[] arr) { if(arr == null){ throw new NullPointerException(); }else{ for (int i = 0; i < arr.length; i++) { System.out.println(arr[i]); } } } }
3.7 try-catch常见问题(视频22)(15‘’)
-
如果 try 中没有遇到问题,怎么执行?
会把try中所有的代码全部执行完毕,不会执行catch里面的代码
-
如果 try 中遇到了问题,那么 try 下面的代码还会执行吗?
那么直接跳转到对应的catch语句中,try下面的代码就不会再执行了
当catch里面的语句全部执行完毕,表示整个体系全部执行完全,继续执行下面的代码
- 如果出现的问题没有被捕获,那么程序如何运行?
那么try…catch就相当于没有写.那么也就是自己没有处理.
默认交给虚拟机处理.
-
同时出现多个异常怎么处理?
出现多个异常,那么就写多个catch就可以了.
注意点:如果多个异常之间存在子父类关系.那么父类一定要写在下面
package com.itheima.exce;
import java.util.Scanner;
public class ExceptionDemo10 {
public static void main(String[] args) {
//1.如果 try 中没有遇到问题,怎么执行? --- 会把try中所有的代码全部执行完毕,不会执行catch里面的代码
//2.如果 try 中遇到了问题,那么 try 下面的代码还会执行吗?
//那么直接跳转到对应的catch语句中,try下面的代码就不会再执行了
//当catch里面的语句全部执行完毕,表示整个体系全部执行完全,继续执行下面的代码
//3.如果出现的问题没有被捕获,那么程序如何运行?
//那么try...catch就相当于没有写.那么也就是自己没有处理.
//默认交给虚拟机处理.
//4.同时有可能出现多个异常怎么处理?
//出现多个异常,那么就写多个catch就可以了.
//注意点:如果多个异常之间存在子父类关系.那么父类一定要写在下面
// method1();
try {
Scanner sc = new Scanner(System.in);
System.out.println("请输入你的年龄");
String line = sc.nextLine();
int age = Integer.parseInt(line);//格式化异常
System.out.println(age);
System.out.println(2 / 0); //数学异常
} catch (Exception e) {
//以后我们针对于每种不同的异常,有可能会有不同的处理结果.
}
System.out.println("测试456");
}
private static void method1() {
try {
Scanner sc = new Scanner(System.in);
System.out.println("请输入你的年龄");
String line = sc.nextLine();
int age = Integer.parseInt(line);//格式化异常
System.out.println(age);
System.out.println(2 / 0); //数学异常
} catch (NumberFormatException e) {
System.out.println("格式化异常出现了");
}catch (ArithmeticException e) {
System.out.println("数学运算异常出现了");
}
System.out.println("测试456");
}
3.8 Throwable中的常见方法(应用)(视频23)(4’’)
-
常用方法
方法名 说明 public String getMessage() 返回此 throwable 的详细消息字符串 public String toString() 返回此可抛出的简短描述 public void printStackTrace() 把异常的错误信息输出在控制台 -
示例代码
package com.itheima.exce; public class ExceptionDemo11 { //public String getMessage() 返回此 throwable 的详细消息字符串 //public String toString() 返回此可抛出的简短描述 //public void printStackTrace() 把异常的错误信息输出在控制台(字体为红色的) public static void main(String[] args) { try { int [] arr = {1,2,3,4,5}; System.out.println(arr[10]);//虚拟机帮我们创建了一个异常对象 new ArrayIndexOutOfBoundsException(); } catch (ArrayIndexOutOfBoundsException e) { /*String message = e.getMessage(); System.out.println(message);*/ /* String s = e.toString(); System.out.println(s);*/ e.printStackTrace(); } System.out.println("嘿嘿嘿"); } }
3.9 异常的练习 (应用) (视频24)(11’’)

-
需求
键盘录入学生的姓名和年龄,其中年龄为18 - 25岁,超出这个范围是异常数据不能赋值.需要重新录入,一直录到正确为止
-
实现步骤
- 创建学生对象
- 键盘录入姓名和年龄,并赋值给学生对象
- 如果是非法数据就再次录入
-
代码实现
学生类
package com.itheima.exce; public class Student { private String name; private int age; public Student() { } public Student(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { if(age >= 18 && age <= 25){ this.age = age; }else{ //自定义异常的目的:为了让异常信息更加的见名知意 throw new RuntimeException("年龄超出了范围"); } } @Override public String toString() { return "Student{" + "name='" + name + '\'' + ", age=" + age + '}'; } }package com.itheima.exce; import java.util.Scanner; public class ExceptionDemo12 { public static void main(String[] args) { // 键盘录入学生的姓名和年龄,其中年龄为 18 - 25岁, // 超出这个范围是异常数据不能赋值.需要重新录入,一直录到正确为止。 Student s = new Student(); Scanner sc = new Scanner(System.in); System.out.println("请输入姓名"); String name = sc.nextLine(); s.setName(name); while(true){ System.out.println("请输入年龄"); String ageStr = sc.nextLine(); try { int age = Integer.parseInt(ageStr); s.setAge(age); break; } catch (NumberFormatException e) { System.out.println("请输入一个整数"); continue; } catch (AgeOutOfBoundsException e) { System.out.println(e.toString()); System.out.println("请输入一个符合范围的年龄"); continue; } /*if(age >= 18 && age <=25){ s.setAge(age); break; }else{ System.out.println("请输入符合要求的年龄"); continue; }*/ } System.out.println(s); } }
3.10 自定义异常(应用)(视频25)(6’’)
1.什么是自定义异常?
当Java中提供的异常不能满足我们的需求时,我们可以自定义异常
2.为什么要自定义异常?
有一个原则 :异常类要与业务相关(见名知意)
3.实现步骤
- 定义异常类
- 写继承关系
- 提供空参/带参构造
4.代码实现
异常类
public class AgeOutOfBoundsException extends RuntimeException {
public AgeOutOfBoundsException() {
}
public AgeOutOfBoundsException(String message) {
super(message);
}
}
学生类
public class Student {
private String name;
private int age;
public Student() {
}
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if(age >= 18 && age <= 25){
this.age = age;
}else{
//如果Java中提供的异常不能满足我们的需求,我们可以使用自定义的异常
throw new AgeOutOfBoundsException("年龄超出了范围");
}
}
@Override
public String toString() {
return "Student{" +
"name='" + name + '\'' +
", age=" + age +
'}';
}
}
测试类
public class ExceptionDemo12 {
public static void main(String[] args) {
// 键盘录入学生的姓名和年龄,其中年龄为 18 - 25岁,
// 超出这个范围是异常数据不能赋值.需要重新录入,一直录到正确为止。
Student s = new Student();
Scanner sc = new Scanner(System.in);
System.out.println("请输入姓名");
String name = sc.nextLine();
s.setName(name);
while(true){
System.out.println("请输入年龄");
String ageStr = sc.nextLine();
try {
int age = Integer.parseInt(ageStr);
s.setAge(age);
break;
} catch (NumberFormatException e) {
System.out.println("请输入一个整数");
continue;
} catch (AgeOutOfBoundsException e) {
System.out.println(e.toString());
System.out.println("请输入一个符合范围的年龄");
continue;
}
/*if(age >= 18 && age <=25){
s.setAge(age);
break;
}else{
System.out.println("请输入符合要求的年龄");
continue;
}*/
}
System.out.println(s);
}
}
异常小结
1.什么是异常
异常就是程序出现了不正常的情况
2.异常的分类
Error & 编译期异常 & 运行时异常
3.如何捕获异常
通过try…catch来捕获
4.故意制造一个异常
throw new 异常类()
5.声明异常(甩锅)
throws
6.为什么要自定义异常
在实际开发过程中有很多异常是jdk没有帮我们定义好的,比如age负数或超出范围异常,
因此我们需要根据实际的业务自定义异常,从而达到见名知意
7.如何自定义异常
继承RuntimeException,调用父类中的空参/带参构造方法
本文概述了如何使用Date类、SimpleDateFormat类处理日期格式化,以及JDK8新引入的时间类如LocalDateTime的用法。深入讲解了异常的概念、分类、处理方式,包括编译时异常和运行时异常的区别,以及自定义异常的实践。
17万+

被折叠的 条评论
为什么被折叠?



