- 0
- 0
- 约7.72万字
- 约 7页
- 2017-06-12 发布于河南
- 举报
Java中异的处理
System.out.println(请输入第一个数:);
int one=input.nextInt();
System.out.println(请输入第二个数:);
int two=input.nextInt();
{System.out.println(两数相除结果为:+one/two);
}catch (InputMismatchException e){
System.out.println(你应该输入整数!!!);
}catch (ArithmeticException e){
System.out.println(除数不能为0);
}catch (Exception e){
System.oy.println(我是不知名异常);
}
System.out.println(程序结束了);
二)try...catch...finally
package com.imooc;
public class TryCatchTest {
public static void main(String[] args) {
// TODO Auto-generated method stub
//在main函数中调用下面的test函数
TryCatchTest tct=new TryCatchTest();
int result=tct.test();//用result接收对象tct的test方法返回值
System.out.println(test()方法执行完毕!返回值为:+result);
int result2=tct.test2();
System.out.println(test2()方法执行完毕!返回值为:+result2);
}
/**
* divider除数
* result结果
* try-catch捕获while循环
* 每次循环,divider减1,result=result+100/divider.
* 如果捕获异常,打印输出“抛出异常”返回-1,否则返回result
*/
public int test(){
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;
}
}
/**
* divider除数
* result结果
* try-catch捕获while循环
* 每次循环,divider减1,result=result+100/divider.
* 如果捕获异常,打印输出“抛出异常”返回result=999,否则返回result
* finally:打印输出”这是finally的应用“,并且打印输出”此时我的result的值“
*/
public int test2(){
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=999);
}finally{
System.out.println(这是finally的应用);
System.out.println(此时我的result的值为+result);
}
}
}
三)
两个重要的关键字:throw和throws1.throws的异常列表可以是抛出一条异常,也可以是抛出多条异常,每个类型的异常中间用逗号隔开2.方法体中调用会抛出异常的方法或者是先抛出一个异常:用throw new Exception()throw是一个动词,写在方法体里,表示“抛出异常”这个动作3.如果某个方法调用了抛出异常的方法,那么必须添加try catch语句去尝试捕获这种异常
public void divide( int one, int two)throws Exception{
if
原创力文档

文档评论(0)