try-catch以及try-catch-finally
来源:互联网 发布:hgkp软件 编辑:程序博客网 时间:2024/05/16 04:26
try-catch以及try-catch-finally
语法:
try{//一些会抛出异常的方法}catch(Exception e){//处理该异常的代码块}finally{//最终将要执行的一些代码}
解释:
(1)如果try抛出异常,程序会终止执行,程序的控制权会转移交给catch块中的异常处理程序
(2)try语句块不可以独立存在,必须与catch或finally块共存
(3)用try-catch语句块处理完异常还需进行一些善后工作,比如关闭连接或关闭打开的一些文件,则用finally语句块进行善后工作
例如:
import java.util.InputMismatchException;import java.util.Scanner;public class Exception{public static void main(String[] args) {Scanner in=new Scanner(System.in);try{int m=in.nextInt();int n=in.nextInt();System.out.println("Sum is "+(m+n));}catch(InputMismatchException e){System.out.println("Incorrect input and re-enter two integers");}}}
运行结果:
i 8
Incorrect input and re-enter two integers
try抛出多种类型的异常:
例如:
public class ExceptionTest{public static void main(String[] args) {Scanner in=new Scanner(System.in);try{System.out.println("请输入第一个数:");int m=in.nextInt();System.out.println("请输入第二个数:");int n=in.nextInt();System.out.println(m+"/"+n+"="+m/n);}catch(InputMismatchException e){System.out.println("输入类型不正确,请输入整数");}catch(ArithmeticException e){System.out.println("除数不能为0");}catch(Exception e){//Exception是InputMismatchException和ArithmeticException两个类的父类}finally{//最终要执行的一些代码}}}
运行结果(三组数据):
请输入第一个数:
3
请输入第二个数:
0
除数不能为0
请输入第一个数:
f
输入类型不正确,请输入整数
请输入第一个数:
4
请输入第二个数:
2
4/2=2
注意:编写多重catch块时要先子类后父类,如上面的代码,Exception要写在最后。
0 0
- try-catch以及try-catch-finally
- try-catch-finally 以及 throw
- java中的异常处理 try-catch 以及try-catch-finally
- try..catch..finally
- try-catch-finally
- Try-catch-finally机制
- 关于try-catch-finally
- C# try catch finally
- try...catch...finally
- try catch finally用法
- Try ---Catch----Finally
- try...catch... finally
- try....catch...finally 妙用
- try{} catch(){}finally{}执行
- Try Catch Finally
- try-catch-finally
- C# try, catch ,finally
- try catch finally
- (函数题)4-8 简单阶乘计算
- 网页涂鸦插件
- Codeforces Round #395 (Div. 2) C. Timofey and a tree (树的基础应用)
- DBCP连接池连接数据库
- 51Nod - 1101 背包
- try-catch以及try-catch-finally
- 用jquery开发手机app起步时遇到的问题
- UVALive - 6525 Attacking rooks
- SplayTree
- atom如何安装插件
- CP30连接池连接数据库
- Python实践 贴吧爬虫
- 如何用JS控制复选框选中,element.checked
- 第一章,作用域是什么