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. MPU6050读取FIFI数据时mpu_dmp_get_data的返回值一直是1

    试验中发现:不断进行循环读fiffo就可以得到正常数据.形如这样 );//返回值:0,DMP成功解出欧拉角 printf("pitch=%f\troll=%f\tyaw=%f\r\n&quo ...

  2. sureface 屏幕残影问题官方解决方案 - 卸载显卡驱动

    您进入桌面,左下角微软图标(单击右键),选择设备管理器,点开“显示适配器”前面的小三角,找到“Intel(r) hd gRAPHICS 520”, 单击右键卸载,卸载的时候不要勾选“删除此设备的驱动软 ...

  3. 在Visual Studio中使用NuGet管理项目库

    NuGet是用来管理项目中引用的各个组件插件什么什么东西的东西,最近使用以后发现对于项目引用的维护非常方便. 暂时转一篇MSDN的文章,其实这个文章的内容就够了: http://msdn.micros ...

  4. python学习之pyc,pyo,pyd文件

    pyc:二进制文件,python文件经过编译器编译之后的文件.可以提高文件加载速度. pyo:二进制文件,优化编译后的文件.可以通过`python -O file.py`生成. pyd:python的 ...

  5. tornado用户验证

    1.重写get_current_user()方法 class BaseHandler(tornado.web.RequestHandler): def get_current_user(self): ...

  6. C#类的修饰符

    ## C#类的修饰符------------------------- public 任何地方可以调用- internal 同一应用程序集内使用- partial 部分类,一个类分成几部分写在不同文件 ...

  7. 基于jquery网站左侧下拉菜单

    网站左侧下拉菜单jQuery代码.这是一款蓝色风格的适合做后台下拉菜单代码.效果图如下: 在线预览   源码下载 实现的代码: <div class="container"& ...

  8. C语言 · 2的次幂表示 · 幂方分解

    蓝桥杯练习场上有两个此类题目: 算法训练 幂方分解   时间限制:1.0s   内存限制:256.0MB        锦囊1 递归. 锦囊2 使用一个函数,递归的进行分解,每次分解的时候要将数字先转 ...

  9. tmpx75 I2C 温度传感器驱动程序添加

    在kernel 内 make menuconfig 加入相关选项 Device Drivers ---> <*> Hardware Monitoring support ---> ...

  10. android——inflater 用法(转)

    在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById().不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例 ...