public class Abnormal
{
//学习JAVA的异常,我们只要记住这几点就可以了
//分为必须处理的异常和可以不处理的异常
//对于必须处理的异常,你怎么处理呢
//可以自己处理,或者让别人处理
//如果是自己处理,就用
//try...catch...finally处理
//让别人处理就是通过throw扔给别人就行了
//深入理解JAVA异常处理机制
//http://blog.csdn.net/hguisu/article/details/6155636
public static void main(String args[])
{
try{
int m=Integer.parseInt(args[0]);
int n=Integer.parseInt(args[1]);
int r=div(m,n);
}catch(ArrayIndexOutOfBoundsException e)
{
System.out.println("main:"+e);
}
}
public static int div(int a,int b)
{
int r=0;
try{
System.out.println("aaa");
r=a/b;
}catch(ArithmeticException e)//算术异常
{
System.out.println(e);
}finally//这里表示不管你抛不抛出异常,都要执行这段代码
{
System.out.println("hello");
}
return r;
}
}
public class Otherabnormal
{
public static void main(String args[])
{
int m=Integer.parseInt(args[0]);
int n=Integer.parseInt(args[1]);
int r=0;
try
{
r=div(m,n);
System.out.println("111");
}catch(ArithmeticException e)
{
System.out.println("gg");
}
System.out.println(r);
}
//扔给你的调用者,如果你扔出去给你的调用者不处理它,也会报错
public static int div(int m,int n)throws ArithmeticException
{
int r;
r=m/n;
return r;
}
}
public class Otherandselfabnormal
{
public static void main(String args[])
{
int m=0;//=Integer.parseInt(args[0]);
int n=0;//=Integer.parseInt(args[1]);
int r=0;
try
{
m=Integer.parseInt(args[0]);
n=Integer.parseInt(args[1]);
r=div(m,n);
}catch(ArithmeticException e)
{
System.out.println("hello");
System.out.println(e);
}catch(NumberFormatException e)//数据格式异常
{
System.out.println("Number format error");
}
}
public static int div(int m,int n)throws ArithmeticException
{
int r=0;
try
{
r=m/n;
}catch(ArithmeticException e)
{
System.out.println("world");
System.out.println(e);
//你这里必须手动抛出异常,不然人家会认为你在这里处理了异常,
//那边就不处理了。
//throw e;
}finally{
//因为我们程序 throw的时候就会返回了,所以它执行throw之前
//就会先去执行finally,执行finally的时候就返回了,导致throw就不会被执行。而你的异常都没throw出去,所以你的main方法就没法捕捉到异常,所以就执行不了异常处理语句。所以说不要到finally后面加上return。
System.out.println("helloworld");
return 0;
}
//return r;
}
}
public class Runtime
{
public static void main(String args[])
{
int m=0;
int n=0;
int r=0;
//因为运行的时候会出现各种各样的异常,我们不想一个一个处理
//我们就直接处理它们的父类,就会处理这个父类下面的各种异常了
try{
m=Integer.parseInt(args[0]);
n=Integer.parseInt(args[1]);
r=div(m,n);
}catch(RuntimeException e)
{
System.out.println("main :"+e);
}
}
public static int div(int m,int n)
{
int r=0;
r=m/n;
return r;
}
}