package shb.java.exception;
/**
* 测试异常类
* @Package:shb.java.exception
* @Description:
* @author shaobn
* @Date 2015-9-7上午11:52:42
*/
public class Demo_2 {
public static void main(String[] args) {
testTD_5();
}
public static void testTD_2(){
TDemo_2 td_2 = new TDemo_2();
try {
td_2.getResult(9, 0);//一旦发生异常,函数中后面的方法不再执行即结束
System.out.println("over");//发生异常后,此句已不能再执行。 直接抛出异常对象,由catch块中异常对象的引用来接收。
} /*catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}*///如果一开始就用Exception会覆盖子异常类,则会只执行Exception,其余都不能执行。
catch (ArithmeticException ae) {
// TODO: handle exception
System.out.println(ae.getMessage());
System.out.println("算术异常");
}catch (ArrayIndexOutOfBoundsException aiobe) {
// TODO: handle exception
System.out.println(aiobe.getMessage());
System.out.println("数组越界异常");
}
System.out.println("helloworld");
}
//自定义异常类
public static void testTD_3(){
TDemo_3 td_3 = new TDemo_3();
try {
td_3.getResult_3(9, 0);
System.out.println("over");
} catch (Exception e) {
// TODO: handle exception
System.out.println(e.getMessage());
}
System.out.println("hellobeijing");
}
//自定义的继承RuntimeException类的异常(编译时是不报错的,运行时检查异常)
public static void testTD_4(){
TDemo_4 td_4 = new TDemo_4();
td_4.getResult(9, 0);
}
public static void testTD_5(){
TDemo_5 td_5 = new TDemo_5();
try {
td_5.testMethod();
} catch (Exception e) {
// TODO: handle exception
System.out.println("异常已经处理");
}
}
}
class TDemo_2{
private int age = 10;
public int getAge(){
return this.age;
}
//声明两个异常,算术异常,数组越界异常。
public int getResult(int a,int b) throws ArithmeticException,
ArrayIndexOutOfBoundsException{
byte[] arr = new byte[a];
b = a/b;
arr[a] = 9;
return a/b;
}
}
class TDemo_3{
private int height = 90;
public int getHeight(){
return this.height;
}
public int getResult_3(int a,int b) throws TDemo_3Exception{
if(b==0)
//抛出自定义异常,必须在方法上声明异常类。
throw new TDemo_3Exception("自定义的异常类");
return a/b;
}
}
//编译时被检测的异常
class TDemo_3Exception extends Exception{
public TDemo_3Exception(String str){
super(str);
}
//重写getMessage()方法
public String getMessage(){
return super.getMessage();
}
}
//编译时不被检测的异常
class TDemo_4Exception extends RuntimeException{
public TDemo_4Exception(String str){
super(str);
}
}
class TDemo_4{
private int with = 90;
public int getWith(){
return this.with;
}
public int getResult(int a,int b){
if(b==0)
throw new TDemo_4Exception("自定义的runtime异常");
return a/b;
}
public void testResult(int a,int b){
if(b<0)
throw new TDemo_4Exception("b小于0");
System.out.println("测试成功");
}
}
class TDemo_5Exception extends Exception{
public TDemo_5Exception(String str){
super(str);
}
}
class TDemo_5{
public void testMethod() throws TDemo_5Exception{
TDemo_4 td_4 = new TDemo_4();
try {
td_4.testResult(9, -1);
} catch (Exception e) {
// TODO: handle exception
throw new TDemo_5Exception("处理失败");
}
}
}