一、Java的异常结构图:
error是系统的问题,程序员无法处理。
exception是程序员可以处理的异常:分为
1、RuntimeException:运行时异常,可以处理也可以不处理
2、左边的,必须处理。
二、
原则:1、先catch子异常,后catch大的异常
2、重写的方法要么和原方法抛出相同的异常,要么不抛出异常
三、代码简单解释
/**
*异常处理
*try throws throw catch finally
*/
import java.io.*;
public class TestEx
{
public static void main(String[] args)
{
int[] arr = {1,2,3};
try
{
System.out.println(arr[4]);//数组越界
}
catch (ArrayIndexOutOfBoundsException xx)
{
System.out.println("打印堆栈信息如下:\n");
xx.printStackTrace();
}
finally//可以用于执行资源清理工作,如:关闭打开的文件、删除临时文件
{
System.out.println("我一定会被执行");
}
/**************************************************/
FileInputStream in = null;
try
{
in = new FileInputStream("myfile.txt");
int b;
b = in.read();
while (b != -1)
{
System.out.print((char) b);
b = in.read();
}
}
catch (FileNotFoundException a)
{
a.printStackTrace();
}
catch (IOException b)
{
System.out.println(b.getMessage());
}
finally
{
try
{
in.close();
}
catch (IOException a)
{
a.printStackTrace();
}
}
}
/********************************************/
void m(int i) throws ArithmeticException
{
if(i == 0)
{
throw new ArithmeticException("被除数为0");
}
}
/********************************************/
//处理不了的异常可以向更高级抛出
void f() throws FileNotFoundException,IOException
{
FileInputStream in = new FileInputStream("myfile.txt");
int b;
b = in.read();
while (b != -1)
{
System.out.print(b);
b =in.read();
}
}
void f2()
{
try
{
f();
}
catch(FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
/**
*自定义异常
*/
class MyException extends Exception
{
private int id;
public MyException(String message,int id )
{
super(message);
this.id = id ;
}
public int getId()
{
return id;
}
}
public class Test
{
public void regist(int num) throws MyException
{
if (num<0)
{
throw new MyException("人数为负值,不合理",4);
}
System.out.println("登记人数"+num);
}
public void manager()
{
try
{
regist(-1);
}
catch(MyException e)
{
System.out.println("等级失败,类型码为:"+e.getId());
e.printStackTrace();
}
System.out.println("操作结束");
}
public static void main(String[] args)
{
Test t = new Test();
t.manager();
}
}