java(12)异常处理
try
{
}
catch(SpecialException e)
{
}
catch(exception ee)
{
}
finally
{
}
package 异常处理; public class YiChang5 { public static void main(String[] args) { // TODO Auto-generated method stub try { int[] a = new int[5]; a[5] = 6; } catch(ArrayIndexOutOfBoundsException e) { System.out.println("该程序发生了数组下标越界异常"); } catch(Exception ee) { System.out.println("该程序发生了异常"); } finally { System.out.println("该语句是肯定执行的"); } } }
import java.net.*;
import java.IO.*;
throws语句是在方法的声明中使用来抛出异常,throw语句是在方法体内使用抛出的异常
自定义异常
class 类名 extends Exception
{
public MyException()
{
}
public MyException(String s)
{
super(s);
}
}
自定义异常:
package 异常处理; public class YiChang5 { public String deiFen(int fen) throws MyException { if(fen>=0&&fen<=100) { return "正常"; } else { throw new MyException("错误输入"); } } public static void main(String[] args) { // TODO Auto-generated method stub YiChang5 yc = new YiChang5(); try { String s = yc.deiFen(68); System.out.println(s); String ss = yc.deiFen(123); System.out.println(ss); } catch(ArrayIndexOutOfBoundsException e) { System.out.println("该程序发生了数组下标越界异常"); } catch(MyException e) { System.out.println("异常信息为:" + e.getMessage()); } catch(Exception ee) { System.out.println("该程序发生了异常"); } finally { System.out.println("该语句是肯定执行的"); } } }