------- android培训、java培训、期待与您交流! ----------
/*以下均为本人按理解手打。仅代表个人观点,如果有错误请联系我加以改成。谢谢!无任何拷贝,摘抄等行为,转载请注明地址*/
异常 Exception
通常用来描述程序的Bug,比如数组越界,空指针引用等等。
在JAVA里:java.lang.Throwable类是所有Exception和Error的超类。也就是说java.lang.Throwable是所有异常和错误的超类。一般程序中出现Error错误,基本没有办法去补救了,而Exception还可以catch。然后加工处理
异常超类为:java.lang.Exception。其中java.lang.RuntimeException是比较有特殊性。因为这个异常可以不用在函数中声明。
比如简单地异常处理:
class division
{
public int div(int a,int b) throws Exception//声明该功能可能会出现问题
{
return a/b;
}
}
class day095
{
public static void main(String[] args)// throws Exception
{
division d = new division();
try
{
int x = d.div(5,2);
System.out.println(x);
}
catch (Exception e)
{
System.out.println("Exception e");
}
//int x = d.div(5,0);
//System.out.println(x);
}
}
代码说明:使用throws声明异常,使用throw抛出异常。使用try发生异常时立即用catch捕获并执行相关信息。
总结:当异常出现的时候,程序会立即终止当前语句,并寻找适应的catch进行捕获。当没有捕获处理时,异常便会传到JVM也就是JAVA虚拟机。但同时也就意味着程序的终止。
自定义异常代码处理:
class fexce extends Exception
{
fexce(String str)
{
super(str);
}
}
class FException
{
static int func(int a,int b)throws fexce
{
if(b<0)
throw new fexce("出现负数");
return a/b;
}
}
class day098
{
public static void main(String[] args)
{
FException fe = new FException();
try
{
int result = fe.func(3,-2);
System.out.println(result);
}
catch (fexce f)
{
System.out.println(f.toString());
}
}
}
代码简单介绍:功能只能判断被除数小余零,声明fexce 异常。并定义构造函数,当被除数小余零时抛出fexec这个异常类并传递详细参数。
总结:自定义异常可以自由定义判定变量合法性,进一步提高了程序的拓展性。这种方式非常简便,自由。
用面向对象的方式来思想异常。就像以Linux的根"/"