1. Try块是什么?

Try块是一块可能产生异常的代码块,一个Try块可能跟着Catch块或者Finally块,或者两者。

Try块的语义:

try{
//statements that may cause an exception
}

2. Catch块是什么?

一个Catch块关联一个Try块,如果在Try块中有一个特定类型的异常发生,则响应的Catch块会执行,例如,

如果在Try块中arithmmetic exception发生,那么对应arithmmetic exception的Catch块会发生。

Catch块的语义:

try
{
//statements that may cause an exception
}
catch (exception(type) e(object))‏
{
//error handling code
}

3. Try-Catch块的执行流程

如果在try块中的异常发生,则执行的控制将会被传到Catch块中,异常被相应的Catch块所捕获,一个

Try块可以有多个Catch块,但是每一个Catch块仅仅能定义一种异常类,

当Try块中的所有代码执行完之后,在Finally块中的代码将会执行。包含一个Finally块并不是强制的,

但是如果你有Finally块,它将会运行,不管有没有异常剖出或者处理。

一个Try-Catch的例子:

class Example1 {
public static void main(String args[]) {
int num1, num2;
try {
// Try block to handle code that may cause exception
num1 = 0;
num2 = 62 / num1;
System.out.println("Try block message");
} catch (ArithmeticException e) {
// This block is to catch divide-by-zero error
System.out.println("Error: Don't divide a number by zero");
}
System.out.println("I'm out of try-catch block in Java.");
}
} 输出: Error: Don't divide a number by zero
I'm out of try-catch block in Java.

4. 在java中的多个代码块

一个Try块可以有多个Catch块

一个捕获Exception类的Catch块可以捕获其他的异常

catch(Exception e){
  //This catch block catches all the exceptions
}

如果有多个Catch块存在,则上面提到的Catch应该放到最后。

如果Try块没有抛出异常,则Catch块将被忽略,程序将会继续。

如果Try块抛出异常,则相应的Catch块将会处理它。

在Catch块中的代码将会执行,然后程序继续执行。

class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}
}
输出:
Warning: ArithmeticException
Out of try-catch block...
												

最新文章

  1. Linux安装JDK1.7
  2. 创建Xml文件与修改Xml文件
  3. 十五个常用的jquery代码段【转】
  4. js中的DOM操作(2)
  5. 分页写入文件,第二次分页前一定要关闭IO流啊。。否则文件写不全。。- -粗心
  6. C# 抽象类和接口的区别
  7. linux驱动系列之文件压缩解压小节(转)
  8. Aircrack-ng官方文档翻译[中英对照]---Aireplay-ng
  9. C#-Mdi多文档窗体及其子窗体的排列 ---ShinePans
  10. ACM题目推荐(刘汝佳书上出现的一些题目)[非原创]
  11. android网络操作使用汇总(http)
  12. 服务端套接字类CxServerSocket的使用
  13. Java-IO之对象输入流输出流(ObjectInputStream和ObjectOutputStream)
  14. tkinter中entry输入控件(四)
  15. Windows安装MongoDB 4.0并赋予用户访问权限
  16. select2 3.5.3 二级下拉及搜索
  17. GIT 工作区和暂存区
  18. python3 zip压缩文件压缩多个不同文件夹内的文件方法
  19. $("this") $(this) 区别
  20. java浅拷贝和深拷贝

热门文章

  1. Android L(5.0)源码之图形与图像处理之动画——Frame、Tween、属性动画、SurfaceView
  2. ucos调度器详解
  3. 网络请求工具--AFNetworking 分类: ios技术 2015-02-03 08:17 76人阅读 评论(0) 收藏
  4. 前段验证框架 formValidator
  5. BZOJ 1455: 罗马游戏 [可并堆]
  6. java实现——003二维数组中的查找
  7. DDD之:Repository仓储模式
  8. javascript中的元素包含判断
  9. UVa 10700 - Camel trading
  10. Android性能优化(一)之启动加速35%