java中的异常类型
捕捉异常的方法:
try...catch...finally的用法
示例:
package com.javalearning;
public class exceptiondemo {
public static void main(String args[]) {
exceptiondemo test=new exceptiondemo();
int result=test.test();
System.out.println("返回值是:"+result);
int result2=test.test2();
System.out.println("返回值是:"+result2);
}
public int test() {//try..catch语句
int divider=10;
int result=100;
try {
while(divider>-1) {
divider--;
result=result+100/divider;
}
return result;
}catch(Exception e)
{
e.printStackTrace();
System.out.println("循环抛出异常。");
return -1;
}
}
public int test2() {//try...catch...finally语句
int divider=10;
int result=100;
try {
while(divider>-1) {
divider--;
result=result+100/divider;
}
return result;
}catch(Exception e)
{
e.printStackTrace();
System.out.println("循环抛出异常。");
return result=666;
}finally {
System.out.println("这里是finally语句!");
System.out.println("result的值是"+result);
}
}
}
异常抛出,使用throws关键字:
package com.javalearn;
public class exceptionthrows {
public void divide(int a,int b) throws Exception {
if(b==0) {
throw new Exception("除数不能为0!");
}
else {
System.out.println("两数相除的结果是:"+a/b);
}
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
int a=3,b=1;
int c=3,s=0;
exceptionthrows e=new exceptionthrows();
/*
e.divide(a,b);
e.divide(c, s);
*/
//使用try...catch语句
try {
e.divide(a, b);
e.divide(c, s);
} catch (Exception g) {
System.out.println(g.getMessage());
}
}
}
package com.javalearn;
public class exceptionthrows {
public void divide(int a,int b) throws Exception {
if(b==0) {
throw new Exception("除数不能为0!");
}
else {
System.out.println("两数相除的结果是:"+a/b);
}
}
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
int a=3,b=1;
int c=3,s=0;
exceptionthrows e=new exceptionthrows();
e.divide(a,b);
e.divide(c, s);
/*
//使用try...catch语句
try {
e.divide(a, b);
e.divide(c, s);
} catch (Exception g) {
System.out.println(g.getMessage());
}
*/
}
}
java中的异常种类:
自定义异常:
package com.javalearn;
public class customException extends Exception{//继承于所有异常的父类Exception
public customException() {
}
public customException(String message) {
super(message);
}
}
package com.javalearn;
public class chainException {
public static void main(String[] args) {
// TODO Auto-generated method stub
chainException chainEx=new chainException();
try{
chainEx.ex2();
} catch(Exception e) {
e.printStackTrace();
}
}
public void ex1() throws customException{//异常1
throw new customException("艰苦奋斗第26天!");
}
public void ex2() {
try {
ex1();
} catch(customException e){
RuntimeException newEx=new RuntimeException("明天要继续奋斗鸭!");
newEx.initCause(e);
throw newEx;
}
}
}