目录
1.概念
java语言的健壮性体现在:
1.GC(守护线程),垃圾回收,回收无用对象,保证充足内存
2.异常处理机制,一段程序出现异常,进行相应处理,不影响其他程序的正常运行
1.1.错误Error
JVM抛出的错误,无法解决,只能终止程序并以良好的方式告知用户。错误出现在JAM。
例如:
//Error演示,出现内存溢出问题,JVM内存空间不足
private static void demo1() {
int array[] = new int[1024*1024*1024];//初始化一个极大的数组
System.out.println(array[0]);
}
1.2.异常Exception
数据不规范造成,可以进行提前预判,不影响其它程序的正常运行,与程序员有关。
常见异常:
NullPointerException 某个变量为null
ArrayIndexOutOfBoundsException index(0-length-1)
ClassCastException: instanceof
ArithmeticException : 除数不能为0
2.异常分类
2.1.运行时异常
一般不做处理,大部分由于程序员编写代码不规范造成的,除了运行时异常(RunTimeException),其它都可以看作编译时异常
例如:空指针异常
public static void main(String[] args) {
demo2(null);
}
//空指针异常
private static void demo2(String[] Array) {
for (String s : Array) {
System.out.println(s+" ");
}
}
2.2.编译异常
1.捕获异常
try{
//有可能出现异常的代码块
}catch(具体的异常类 变量){
//处理捕获到的异常对象
}finally{
//不管是否出现异常都会执行的逻辑
//释放物理资源
}
其中finally可省略
//线程
try{
//上锁
}finally{
//解锁
}
//try...catch
private static void demo3() {
int n=0,m=0,t=100;
try {
m = Integer.parseInt("888");//把String类型数据转为整型数据
n = Integer.parseInt("ab88");//发生异常转向catch
t = 77; //t没有机会被赋值
}catch (NumberFormatException e){
System.err.println("发生异常:"+e.getMessage());
}
System.out.println("m="+m+" n="+n+" t="+t);
}
2.throws关键字抛出
谁调用throws的方法,就把异常抛给调用者(上级)是一种消极处理,没有真正的处理异常。
private static void demo4() throws ClassNotFoundException, ParseException {
Class.forName("com.exception.Exceptiondemo");
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-<<-dd HH:mm:ss");
dateFormat.parse("2021-7-16 12:00:00");
}
3.throw
throw new 异常类()
产生异常:1.控制流程;2.与自定义异常类结合使用。
public void setAge(int age) {
//18-30 抛出异常 提示信息
if (age < 18 || age > 30) {
try {
throw new UserInfoException(age + "年龄不合法,自动设置年龄默认值");
} catch (UserInfoException e) {
e.printStackTrace();
age = 18;
}
}
this.age = age;
}
3.自定义异常类
public class UserInfoException extends Exception{
public UserInfoException(String message) {
super(message);
}
public UserInfoException(String message, Throwable cause) {
super(message, cause);
}
public UserInfoException(Throwable cause) {
super(cause);
}
}