The try/catch statement encloses some code and is used to handle errors and exceptions that might occur in that code. Here is the general syntax of the try/catch statement:

    try {
body-code
} catch (exception-classname variable-name) {
handler-code
}

The try/catch statement has four parts. The body-code contains code that might throw the exception that we want to handle. The exception-classname is the class name of the exception we want to handle. The variable-name specifies a name for a variable that will hold the exception object if the exception occurs. Finally, the handler-code contains the code to execute if the exception occurs. After the handler-code executes, execution of the thread continues after the try/catch statement. Here is an example of code that tries to create a file in a non-existent directory which results in an IOException.

    String filename = "/nosuchdir/myfilename";
try {
// Create the file
new File(filename).createNewFile();
} catch (IOException e) {
// Print out the exception that occurred
System.out.println("Unable to create "+filename+": "+e.getMessage());
}
// Execution continues here after the IOException handler is executed

Here's the output:

    Unable to create /nosuchdir/myfilename: The system cannot find the path specified

It is possible to specify more than one exception handler in a try/catch statement. When an exception occurs, each handler is checked in order (i.e. top-down) and the handler that first matches is executed. The following example registers a name at a website. The example code can throw two kinds of exceptions -- one if the URL is invalid and one if the web page is not accessible. This example uses an invalid URL which results in a MalformedURLException.

    // This URL string is deliberately missing the http: protocol to cause an exception
String urlStr = "xeo.com:90/register.jsp?name=joe";
try {
// Get the image
URL url = new URL(urlStr);
InputStream is = url.openStream();
is.close();
} catch (MalformedURLException e) {
// Print out the exception that occurred
System.out.println("Invalid URL "+urlStr+": "+e.getMessage());
} catch (IOException e) {
// Print out the exception that occurred
System.out.println("Unable to execute "+urlStr+": "+e.getMessage());
}

Here's the output:

    Invalid URL xeo.com:90/register.jsp?name=joe: no protocol: xeo.com:90/register.jsp?name=joe

Here is the same example with a valid URL. The URL refers to a non-existant web page which results in a IOException.

    urlStr = "http://xeo.com:90/register.jsp?name=joe";
try {
URL url = new URL(urlStr);
InputStream is = url.openStream();
is.close();
} catch (MalformedURLException e) {
// Print out the exception that occurred
System.out.println("Invalid URL "+urlStr+": "+e.getMessage());
} catch (IOException e) {
// Print out the exception that occurred
System.out.println("Unable to execute "+urlStr+": "+e.getMessage());
}

Here's the output:

    Unable to execute http://xeo.com:90/register.jsp?name=joe: Connection refused: connect

When an exception occurs, the exception is compared with the specified exception class name using the instanceof comparator. This means that if the handler specifies a class name E, then any exception whose class either equals E or is a subclass of E, matches the handler. The following example catches either MalformedURLException or IOException using Exception since both exceptions are subclasses of Exception.

    urlStr = "http://xeo.com:90/register.jsp?name=joe";
try {
URL url = new URL(urlStr);
InputStream is = url.openStream();
is.close();
} catch (Exception e) {
// Print out the exception that occurred
System.out.println(urlStr+": "+e.getMessage());
}

Here's the output:

    http://xeo.com:90/register.jsp?name=joe: Connection refused: connect

If an exception occurs and does not match any of the handlers, the exception is passed to any enclosing try/catch statements and up the call chain until it is caught by some handler. If the exception is not handled by any handler, it becomes an uncaught exception and the thread is immediately terminated. In the following example, a NullPointerException is thrown, which is not caught by MalformedURLException and so becomes an uncaught exception.

    // This string is deliberately set to null to cause an exception
urlStr = null;
try {
int len = urlStr.length(); // Causes a NullPointerException
URL url = new URL(urlStr);
} catch (MalformedURLException e) {
// Print out the exception that occurred
System.out.println("Invalid URL "+urlStr+": "+e.getMessage());
}

The result of an uncaught exception is a stack trace that identifies the line of code that threw the exception. The output looks something like:

    Exception in thread "main" java.lang.NullPointerException
at MyClass.mymethod(MyClass.java:162)
Related Examples

e1087. try/catch语句的更多相关文章

  1. Java异常处理中finally中的return会覆盖catch语句中的return语句

    Java异常处理中finally中的return会覆盖catch语句中的return语句和throw语句,所以Java不建议在finally中使用return语句 此外 finally中的throw语 ...

  2. Java 多重catch语句的具体使用介绍

    某些情况,由单个代码段可能引起多个异常.处理这种情况,你可以定义两个或更多的catch子句,每个子句捕获一种类型的异常.当异常被引发时,每一个catch子句被依次检查,第一个匹配异常类型的子句执行.当 ...

  3. 作用域&作用域链和with,catch语句&闭包

    作用域(函数) 作用域:变量与函数的可访问范围,即作用域控制着变量与函数的可见性和生命周期; 在一些类C编程语言中花括号内的每一段代码都有各自的作用域,而且变量在声明它们的代码段外是不可见的,称之为块 ...

  4. C# try catch语句&获取随机数的方法

    try catch语句: try{ //无论如何都会走,必须写: } catch(Exception a){ //Exception报异常,需要定义,需要写输出语句: //如果上面执行失败走,必须写: ...

  5. Java知多少(47)多重catch语句的使用

    某些情况,由单个代码段可能引起多个异常.处理这种情况,你可以定义两个或更多的catch子句,每个子句捕获一种类型的异常.当异常被引发时,每一个catch子句被依次检查,第一个匹配异常类型的子句执行.当 ...

  6. Atitit. Java script 多重多重catch语句的实现and Javascript js 异常机制

    Atitit. Java script 多重多重catch语句的实现and Javascript js 异常机制 1. 语法错误(ERROR)和运行期错误(Exception) 1 2. 错误类型判断 ...

  7. 一个try可以跟进多个catch语句,用于处理不同情况,当一个try只能匹配一个catch

    一个try可以跟进多个catch语句,用于处理不同情况.当一个try只能匹配一个catch. 我们可以写多个catch语句,但是不能将父类型的exception的位置写在子类型的excepiton之前 ...

  8. try...catch 语句

    一般情况下,我们很少用到 try...catch 语句,但是有时候为了测试代码中的错误,也有可能会用到.小白我也在工作中用到过.那么好的程序设计,什么时候会用到呢? try...catch 一般用来捕 ...

  9. 六. 异常处理5.多重catch语句的使用

    某些情况,由单个代码段可能引起多个异常.处理这种情况,你可以定义两个或更多的catch子句,每个子句捕获一种类型的异常.当异常被引发时,每一个catch子句被依次检查,第一个匹配异常类型的子句执行.当 ...

随机推荐

  1. unity5, Configurable Joint: Anchor, Connected Anchor, Auto Configure Connected Anchor

    configurable joint加在轮子上,connected body是车身. 这种情况下,Anchor=(0,0,0)表示轮子一端joint锚点取carWheelCenter Connecte ...

  2. SQL查询刚開始学习的人指南读书笔记(二)创建SQL查询

    PARTII: SQL Basics CHAPTER 4Creating a Simple Query 介绍一种怎样创建SQL语句的技术--"Request/Translation/Clea ...

  3. Java并发编程之并发代码设计

    引子 之前的文章我们探讨了引发线程安全的原因主要是由于多线程的对共享内存的操作导致的可见性或有序性被破坏,从而导致内存一致性的错误.那么如何设计并发代码解决这个问题呐?我们一般使用这几种方式: 线程封 ...

  4. oracle triggers 实现两个结构相同的表的数据级联更新操作

    首先创建两个结构相同的表 -- Create table create table TABLE_TEMP ( userid NUMBER not null, username NVARCHAR2(50 ...

  5. javascript高级:原型与继承

    原型继承的本质就是一条原型链,对象会沿着这条链,访问链里的方法属性. 对象的__proto__属性就是用于访问它的原型链的上一层: 考虑以下对象: 1. 所有对象的原型: Object.prototy ...

  6. linux 2.6.xx自动加载kvm模块

    在文件夹/etc/udev/rules.d/中添加文件65-kvm.rules,文件内容如下: KERNEL=="kvm", MODE="0660", GROU ...

  7. ny2 括号配对问题

    括号配对问题 时间限制:3000 ms  |  内存限制:65535 KB 难度:3   描述 现在,有一行括号序列,请你检查这行括号是否配对.   输入 第一行输入一个数N(0<N<=1 ...

  8. java.util.logging.Logger使用详解 (转)

    http://lavasoft.blog.51cto.com/62575/184492/ ************************************************* java. ...

  9. pyv8使用总结

    在使用python爬虫的过程中,难免遇到要加载原网站的js脚本并执行.但是python本身无法解析js脚本. 不过python这么猛的语言,当然设置了很多方法来执行js脚本.其中一个比较简单的方法是使 ...

  10. 一款基于jquery滑动后固定于顶部的导航

    之前已为大家介绍了好多css3实现的导航菜单.今天分享一款基于jquery滑动后固定于顶部的导航.这款导航的特点是初始位于顶部下面一百个像素,当鼠标滚动时到下方,导航一直处于顶部.效果图如下: 在线预 ...