异常
广义上: 所有的不正常情况
错误:程序运行时的,但是不是程序能够处理的,例如 虚拟机内存不够用.
狭义异常:程序在运行时出现的错误
经过异常处理机制后,程序可以继续向下执行.
public class day1 {
public static void main(String[] args) {
/*
1.数组索引越界 java.lang.ArrayIndexOutOfBoundsException
*/
/*int [] a = new int[2];
a[2]=5 ;*/
/*
2.空指针异常 java.lang.NullPointerException
*/
/*String S=null;
System.out.println(S.length());*/
/*
3.类型转换异常java.lang.ClassCastException
*/
/*Object obj = "abc";
Integer in = (Integer) obj;*/
/*
4.数字格式化异常 java.lang.NumberFormatException
*/
/*new Integer("abc");*/
/*
5.算数异常
java.lang.ArithmeticException / by zero
*/
//int x=10/0;
//异常处理机制,有的异常不强制处理,有的需要强制处理
try{
String s = "utf-8";
byte [] b = "abc".getBytes(s);
}catch (UnsupportedEncodingException s){
System.out.println("编译错误");
}
System.out.println("代码");
}
异常的体系
Trowable
Error:错误,不学习
Exception:异常,学习重点
运行时的异常:
直接或者间接继承RuntimeException
在编译期间不强制进行处理
编译时异常:
直接或间接继承Exception,与RuntimeException没有关系
在编译期间强制进行处理,否则不进行编译
异常处理
package com.ff.javaexception;
public class Demo2 {
public static void main(String[] args) {
/* try{
可能异常的代码;
}catch (异常类型(只捕获指定类型的异常)){
处理异常的代码;
}*/
try {
String s1=null;
s1.length();
/* try {
String[] s = new String[]{"1", "2", "3"};
s[3] = "3";
}catch (ArrayIndexOutOfBoundsException s){
System.out.println("溢出异常");
}*/
String[] s = new String[]{
"1", "2", "3"};
s[3] = "3";
int x=10;
int y =0;
int t = x/y;
System.out.println("可能异常后面的代码");
}catch (ArithmeticException s){
System.out.println("算数异常");
}catch (ArrayIndexOutOfBoundsException s){
System.out.println("溢出异常");
}catch (Exception e){
System.out.println("有异常,不知道啥异常");
}
System.out.println("后面的代码");
}
}