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. Objective-C中的@Property具体解释

    Objective-C中的@Property具体解释 @Property (属性) class vairs 这个属性有nonatomic. strong. weak, retain. copy等等 我 ...

  2. Linux使用技巧5--格式化U盘

    通常来说,格式化一个分区的U盘还是非常easy的.仅仅须要使用mkfs命令指定目标文件系统就能够了,样例例如以下: $ sudo fdisk -l $ sudo mkfs -t vfat /dev/s ...

  3. [转]VTH changes in DC from Hspice

    Hello, everyone. I’d like to know the threshold of the MOS transistor. And I found the “.print vth() ...

  4. [hihoCoder] #1093 : 最短路径·三:SPFA算法

    时间限制:10000ms 单点时限:1000ms 内存限制:256MB 描述 万圣节的晚上,小Hi和小Ho在吃过晚饭之后,来到了一个巨大的鬼屋! 鬼屋中一共有N个地点,分别编号为1..N,这N个地点之 ...

  5. 【Android】10.5 滚动视图(RecyclerView)

    分类:C#.Android.VS2015: 创建日期:2016-02-19 一.简介 滚动视图(RecyclerView)的用法与布局控件的用法类似,唯一不同的是,所有布局控件中都可以包含多个组件,而 ...

  6. Linux系统CPU的性能监控及调优

    前言: 性能优化是一个老生常谈的话题,典型的性能问题如页面响应慢.接口超时,服务器负载高.并发数低,数据库频繁死锁等.尤其是在“糙快猛”的互联网开发模式大行其道的今天,随着系统访问量的日益增加和代码的 ...

  7. java web 自定义的权限框架

    权限框架2部分 1.认证  (通常指登录) 2.授权   (指用户访问改页面是否有权限) 设计:

  8. Android开发日记(二)

    HashMap<String, Object> map;定义一个HashMap用来传递字符 TextView textView_JobTitle=(TextView)findViewByI ...

  9. iOS NSURLConnection使用详解

    一.整体介绍 NSURLConnection是苹果提供的原生网络访问类,但是苹果很快会将其废弃,且由NSURLSession(iOS7以后)来替代.目前使用最广泛的第三方网络框架AFNetworkin ...

  10. 一款基于css3非常实用的鼠标悬停特效

    今天给大家带来一款基于css3非常实用的鼠标悬停特效.这款特效,当鼠标经过时候一个半透明的遮罩层倒下来.效果很好,而且是纯css3实现的,代码很少,非常实用. 效果如下: 在线预览   源码下载 实现 ...