1. 异常分类
Exception 和 Error 都继承 Throwable 基类。异常分为系统错误(Error)和 Exception,Exception 又分为 RuntimeException 和其他异常。
2. 异常的代码块结构
try{
int[] a = {1,2,3};
int x = a[3];
String s = null;
s.length();
int c = 10,d = 0;
int e = c/d;*/
}catch(ArrayIndexOutOfBoundsException e){
System.out.println("数组越界");
temp = 200;
}catch(NullPointerException e){
System.out.println("空指针异常");
}catch(ArithmeticException e){
System.out.println("算术异常");
}finally{
temp = 200;
System.out.println("都要执行。。。");
}
异常的代码块结构如上,一个 try 可以配多个 catch 和一个 finally。当 try 中的代码出现异常时,异常由 catch 尝试捕获,不然运行结果如何,finally 中的代码一定会执行。
3. 异常处理
异常处理分为 捕获异常(try:{}catch:{})和抛出异常(throws)。当一个对象 throws 异常后,这个异常必须在上层继续 throws 或进行捕获处理,最终总要有一个地方将异常捕获处理。
import java.io.FileInputStream;
import java.io.FileNotFoundException;
public class Test {
public static void main(String[] args) {
// 由于 test4() 可能会抛出异常,此处需要做try catch 捕获
// 或者再main函数处继续抛出
try {
test4();
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
// 异常处理分类2:throws 抛出异常,由其他地方进行捕获
static void test4() throws FileNotFoundException{
FileInputStream in = new FileInputStream("");
}
// 异常处理分类1:try catch 捕获异常并处理
static void test1(){
try{
int[] a = {1,2,3};
int x = a[3];
}catch(Exception e){
e.printStackTrace();
}
}*/
}
4. 自定义异常
// 自定义一个异常,MyException,extends Exception
class MyException extends Exception{
public MyException(String str){
super(str);
}
}
// 定义一个 Pan 类,当属性 p>500 时,会抛出异常 MyException
class Pan{
int p;
public Pan(int p){
this.p = p;
}
public void use()throws MyException{
if(p>500){
// throws MyException时,需要 new 一个对象
throw new MyException("压力太大,注意安全,有异常...");
}else{
System.out.println("压力正常,安全使用...");
}
}
}
public class Test {
// main 函数中进行测试
public static void main(String[] args) {
// 调用 test() 时,要主动捕获它抛出的异常
try {
test();
} catch (MyException e) {
e.printStackTrace();
}
// 调用 p.use 时
Pan p = new Pan(3000);
try {
p.use();
} catch (MyException e) {
e.printStackTrace();
}
}
// 当 变量 a < 0时,throws MyException
static void test() throws MyException{
int a = -1;
if(a<0){
// throws MyException时,需要 new 一个对象
throw new MyException("异常发生了");
}else{
System.out.println("没有异常");
}
}
}