java异常,日期
异常
异常就是程序在执行过程中出现的非正常的情况,最终会导致jvm的非正常停止。(语法错误不算在异常体系中)
异常概述
Error:严重问题,通过代码无法处理 如:内存溢出。
Exception:称为异常类,它表示程序本身可以处理的问题。
RuntimeException及其子类:运行时异常。(空指针异常,数组下标越界异常)
除RuntimeException之外所有的异常:编译时期必须处理的,否则程序不能通过编译。(日期格式化异常)
编译时异常,是在编译成class文件时必须要处理的异常,也称之为受检异常
运行时异常,在编译成class文件不需要处理,在运行字节码文件时可能出现的异常,也称之为非受检异常。
异常处理方式
java中异常处理是通过5个关键字来实现的:
try:执行可能产生异常的代码
catch:捕获异常( 如果catch块没有处理相关的异常,那么这个异常会被继续网上抛,最终交给就jvm处理,这是程序会终止)
finally:无论是否发生异常,代码总能执行
throw:手动抛出异常对象
throws:声明方法中可能抛出的各种系统异常,写在方法上,可以写很多异常类型。
自定义异常
定义类UserNotFindException继承Exception,或者Throwable或者RuntimeException并添加构造方法
package com.jifu.test;
public class UserNotFindException extends Throwable {
public UserNotFindException() {
}
public UserNotFindException(String message) {
super(message);
}
public UserNotFindException(String message, Throwable cause) {
super(message, cause);
}
public UserNotFindException(Throwable cause) {
super(cause);
}
public UserNotFindException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
}
}
package com.jifu.test;
import java.util.Scanner;
public class Test {
public static void main(String[] args) {
String userName = "zhangsan";
Scanner scanner = new Scanner(System.in);
System.out.println("请输入用户名:");
String name = scanner.next();
if (userName.equals(name)){
System.out.println("用户存在");
}else {
try{throw new UserNotFindException("账号或者密码错误");}catch (UserNotFindException e){
e.printStackTrace();
}
}
}
}
输出:
日期
世界标准时间:格林尼治/格林威治时间(Greenwith Mean Time)简称GMT。
计算机中的时间起始点:1970年1月1日 00:00:00
long start = System.currentTimeMillis();//获得1970年1月1日 00:00:00到现在的毫秒数。
Date
public Date():获得当前时间的时间对象,
public Date(long s); //s时间戳该方法可以灵活的设置想要的时间点。
SimpelDateFormat
日期格式化类
1、public SimpleDateFomat() //使用默认格式
2、public SimpleDateFomat(String pattern) //使用指定的格式
解析日期:
1格式化:
public final String format(Date date):将日期格式化成想要的格式。
2解析:
public Date parse(String source):将字符串解析成日期。