目录
一、结构:
二、 异常类型:
1.异常Exception:
public class Demo1 {
public static void main(String[] args) {
/*int [] a=new int[5];
a[5]=1;
ArrayIndexOutOfBoundsException 数组检索超过范围*/
/*String s=null;
s.length();
NullPointerException 空指针异常*/
/*Integer.parseInt("asd");
NumberFormatException 数字格式化异常*/
/*Object s="sdf";
int a=(int)s;
ClassCastException 类型转换异常*/
/*System.out.println(10/0);
ArithmeticException*/
}
}
2.错误Error:
public class Demo2 {
public static void main(String[] args) {
/*
Error
堆溢出与栈溢出
*/
//堆溢出
ArrayList arr=new ArrayList();
while(true){
arr.add(1);
}
}
//栈溢出
public static int P(int n){
if(n==1){
return 1;
}
else{
P(n-1);
}
return 1;
}
}
三、异常处理:
1.catch:
catch括号中若是父类,则只能放在所有catch的最后;
切忌在catch里什么都不写,这样在开案发过程中会认为没有问题;
try中代码一旦异常,就不会执行后面的代码,转而执行对象异常的catch块,
处理完后再执行后面的代码;
public class Demo3 {
public static void main(String[] args) {
try {
int a = 10;
int b = 0;
int c = a / b;
}catch(ArithmeticException n){
n.printStackTrace();
System.out.println("除数不可为零!");
} catch (NullPointerException a){
a.printStackTrace();
System.out.println("对象为null");
}catch (Exception e){
e.printStackTrace();
System.out.println("错误");
}
System.out.println("jj");
}
}
2.Finally:
public class Demo4 {
public static void main(String[] args) throws IOException {
FileInputStream in=null;
try{
in=new FileInputStream("D:/oooo");
in.read();
} catch (FileNotFoundException f){
f.printStackTrace();
System.out.println("找不到文件");
}catch (IOException e) {
e.printStackTrace();
System.out.println("文件不可读");
}finally {
if(in!=null){
in.close();
}
}
}
}
3.throw:
在方法声明的地方,通过throws关键字,声明此方法可能抛出的异常 任何方法都可以使用throws关键字抛出异常,包括抽象方法;
public class Demo5 {
public static void main(String[] args) {
chu(10,0);//由于chu的方法,抛出的是运行期的异常,所以在编译期间不会要求强制处理,需要程序员注意
try {
test();//test方法中抛出的是编译期异常,所以会在写代码期间,强制要求进行处理;
//处理方法有两种,1.try catch 捕获处理 2.继续throws抛出,一般到顶层方法就不能再throws了;
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
public static int chu(int a,int b)throws ArithmeticException{
int c=a/b;
return c;
}
public static void test() throws UnsupportedEncodingException {
"sdf".getBytes("utf-8");
}
}