Calendar类
输出今天是今年中的第几天,第几周
public static void main(String[] args) {
Calendar c=Calendar.getInstance();
int day=c.get(Calendar.DAY_OF_YEAR);
int week=c.get(Calendar.WEEK_OF_YEAR);
int month=c.get(Calendar.MONTH);
month+=1;
int year=c.get(Calendar.YEAR);
System.out.println(month+"\t"+year+"今天是今年的"+day+"天, 今天是今年的"+week+"周");
}
异常
常见的运行时异常
NullPointerException 空指针异常(一个对象没有初始化调用方法)
IndexOutOfBoundsException 下标越界异常
ClassCastException 类型转换异常(对象类型转换时)
NumberFormatException 数字格式异常
ArithmeticException 算术异常
非运行时异常(编译时异常)
非运行时异常:编译异常或检查异常,
在程序设计过程中,编译时就会被发现,但是执行时可能发生也可能不发生的异常,为了程序不报错可以执行,那么这一类异常必须进行相应的处理
Exception的子类包括Exception,除了RuntimeExcption之外都属于编译时异常。
Exception类:异常的父类。
Error类:错误,错误比较严重的问题,不属于异常,程序猿无法处理。
OutofMemory 堆内存 解决办法:JVM调优
StackOutOfFlow
异常处理
Java的异常处理是通过5个关键字来实现的:
- try:执行可能产生异常的代码
- catch:捕获异常 ,并处理
- finally:无论是否发生异常,代码总能执行
- throw: 手动抛出异常
- throws:声明方法可能要抛出的各种异常
throws关键字:声明异常
使用原则:底层代码向上声明或者抛出异常,最上层一定要处理异常,否则程序中断。
public static void divide() throws Exception {
//可能出现异常的代码
}
public static void main(String[] args) {
try {
divide();
} catch (Exception e) {
e.printStackTrace();
}
}
或
public static void main(String[] args) throws Exception {
divide();
}
自定义异常类
i.自定义异常: 继承Exception或RuntimeException
ii.在此类中定义构造方法,调用父类中的带字符串参数的构造方法(此字符串表示对异常的描述)
鼠标右键-》 Generator Constructor from Superclass
iii.使用异常
package com.qf.day14_4;
/**
* 性别异常
*
*/
public class SexException extends RuntimeException {
public SexException() {
super();
// TODO Auto-generated constructor stub
}
public SexException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
// TODO Auto-generated constructor stub
}
public SexException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
public SexException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public SexException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
}
使用
public void setSex(String sex) {
if(sex.equals("男")||sex.equals("女")) {
this.sex = sex;
}else {
//抛出异常
throw new SexException("性别有错误");
}
}