什么是异常?
首先,异常不是我们平常写代码的时候少一个“;”,打错一个字母所带来的无法运行的语法错误。而是无法通过代码来规避的问题:比如:
-输入格式有问题
-读取文件的时候,文件被强制删除
-网络传输文件的时候中途断网
这些问题,才能被称为异常:
package Exception;
public class Exc {
/*
什么是异常?
-程序运行中不正常的情况:无法靠代码进行规避的问题
-在程序运行的时候:
-输入格式有问题
-读取文件的时候文件被强制删除
-网络传输的过程中断网了
-这些都被称为异常,异常不包含语法错误
-最早的不正常:数组越界
Java中默认的异常处理机制:
-当程序出现异常后,会将一场包装在一个对应的对象中,并抛出此对象
常见的异常:
异常的体系结构:
Java.lang.Throwable 根父类
-两个常用的方法:
-public void printStackTrace();打印异常信息
-public String getMassage();获取到异常信息
-两个子类:
-Error:错误
-Exception:异常
*/
public static void main(String[] args) {
//ArrayIndexOutOfBoundsException 数组越界异常
//int[] a=new int[5];
//a[5]=5;
//StringIndexOutOfBoundsException 索引越界异常
//String str="andjs";
//str.charAt(9);
//ArithmeticException 算术异常
//int a=10;
//int b=0;
//int c=a/b;//并非问题所在,只是问题的爆发点
//NullPointerException 指针异常
//String s=null;
//s.length();
//ClassCastException 类型转换不兼容异常
//Object o="ajis";
//Integer i=(Integer)o;
//NumberFormatException 类型转换错误
//int n=Integer.parseInt("abc");
System.out.println("后面的程序");
}
}
上述代码说明的是其中的Exception类型的异常,接下来看看Error类型的异常:
Error是错误类型,该类一般是程序运行时的严重问题,通常是由于系统错误或者资源耗尽的问题所导致的,常见的有以下两种:OutOfMemoryError、StackOverflowError:
package Exception;
import java.util.ArrayList;
import java.util.Date;
public class Error {
/*
Error 错误
*/
public static void main(String[] args) {
ArrayList arrayList=new ArrayList();
while(true){
arrayList.add(new Date());
}
//OutOfMemoryError 堆爆了(存放对象的空间)
// sum(10000000);
//栈溢出 StackOverflowError
}
public static int sum(int n){
if(n==1){
return 1;
}
return sum(n-1);
}
}
关于是否继承Runtime类的问题:
继承了Runtime的类:如上述代码展示的Exception的例子,这些就是继承了Runtime类,与没有继承的区别在于继承了Runtime的类可以选择处理或者不处理,而没有继承的需要在代码中进行处理
如何处理异常:
一般我们使用try-catch语句来对异常进行处理:
package Exception;
public class Exeption_Over {
/*
Exception:出现的一般问题,可以使用java中的异常机制处理的
-RuntimeException:运行时异常
-刚才那六种都是运行时异常
-:非运行时异常
在写代码的时候就要根据不同的情况设定好处理程序
运行程序之后如果出现问题,就执行异常处理程序,如果运行是没有出现问题
那么就不需要执行异常处理程序了
关键字:
try{
}
catch{
//catch可以多写几个
}
finaly{
}
*/
public static void main(String[] args) {
/* try{
String s=null;
int a=10;
int b=0;
int c=a/b;
}catch (ArithmeticException a){
a.printStackTrace();
String str=null;
System.out.println("除数不能为零:"+a.getMessage());
}catch (NullPointerException n){
n.printStackTrace();
}finally {
System.out.println("空指针异常");//多次输出”空指针异常的时候可以直接写在最后finally之中
}*/
test();
}
public static int test(){
try{
int a=10;
int b=0;
int c=a/b;
}catch(ArithmeticException a){
return -1;
}finally {
System.out.println("算数错误");
}
return 0;//无论如何都会走一次finally
}
final与finally的区别:
final:是关键字,最早在String类型的底层代码实现中看见,一但被final类型关键字修饰,就无法对其内容进行修改,因此也导致String类型进行内容操作的时候要不断地创建新对象
finally:是执行语句,被finally框定的内容是在抛出异常这个结构中无论如何都要执行的语句