e1087. try/catch语句
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语句的更多相关文章
- Java异常处理中finally中的return会覆盖catch语句中的return语句
Java异常处理中finally中的return会覆盖catch语句中的return语句和throw语句,所以Java不建议在finally中使用return语句 此外 finally中的throw语 ...
- Java 多重catch语句的具体使用介绍
某些情况,由单个代码段可能引起多个异常.处理这种情况,你可以定义两个或更多的catch子句,每个子句捕获一种类型的异常.当异常被引发时,每一个catch子句被依次检查,第一个匹配异常类型的子句执行.当 ...
- 作用域&作用域链和with,catch语句&闭包
作用域(函数) 作用域:变量与函数的可访问范围,即作用域控制着变量与函数的可见性和生命周期; 在一些类C编程语言中花括号内的每一段代码都有各自的作用域,而且变量在声明它们的代码段外是不可见的,称之为块 ...
- C# try catch语句&获取随机数的方法
try catch语句: try{ //无论如何都会走,必须写: } catch(Exception a){ //Exception报异常,需要定义,需要写输出语句: //如果上面执行失败走,必须写: ...
- Java知多少(47)多重catch语句的使用
某些情况,由单个代码段可能引起多个异常.处理这种情况,你可以定义两个或更多的catch子句,每个子句捕获一种类型的异常.当异常被引发时,每一个catch子句被依次检查,第一个匹配异常类型的子句执行.当 ...
- Atitit. Java script 多重多重catch语句的实现and Javascript js 异常机制
Atitit. Java script 多重多重catch语句的实现and Javascript js 异常机制 1. 语法错误(ERROR)和运行期错误(Exception) 1 2. 错误类型判断 ...
- 一个try可以跟进多个catch语句,用于处理不同情况,当一个try只能匹配一个catch
一个try可以跟进多个catch语句,用于处理不同情况.当一个try只能匹配一个catch. 我们可以写多个catch语句,但是不能将父类型的exception的位置写在子类型的excepiton之前 ...
- try...catch 语句
一般情况下,我们很少用到 try...catch 语句,但是有时候为了测试代码中的错误,也有可能会用到.小白我也在工作中用到过.那么好的程序设计,什么时候会用到呢? try...catch 一般用来捕 ...
- 六. 异常处理5.多重catch语句的使用
某些情况,由单个代码段可能引起多个异常.处理这种情况,你可以定义两个或更多的catch子句,每个子句捕获一种类型的异常.当异常被引发时,每一个catch子句被依次检查,第一个匹配异常类型的子句执行.当 ...
随机推荐
- hibernate,动态更新,插入 dynamic-insert,dynamic-update 我有话要说 ---稍后整理
http://dreamzhong.iteye.com/blog/1207377 http://blog.csdn.net/hsuxu/article/details/8108326 @org.hib ...
- django 连接mysql 数据库
1.新建一个mysite项目:django-admin startproject mysite 2.进入项目目录,新建一个app : python manage.py startapp polls 3 ...
- appium +uiautomator2 遇到 deviceName can't be blank 提示的解决
为了获取android toast ,需要升级selenium 到 3.4.0 和appium 5.0.0-BETA9 到最新版本,并在启动代码前面追加一行代码: capabilities.setCa ...
- django找不到模板(TemplateDoesNotExist at)的异常处理案例
一.django的渲染模板时报如下错: TemplateDoesNotExist at 二.定位问题: 1.由上面报的错.一开始以为是找不到模板(自己路径写的不对).后来发现我的路径写的是正确的. 2 ...
- [Jobdu] 题目1529:棋盘寻宝
题目描述: 现在有一个8*8的棋盘,上面放着64个价值不等的礼物,每个小的棋盘上面放置一个礼物(礼物的价值大于0小于1000),一个人的初始位置在棋盘的左上角,每次他只能向下或向右移动一步,并拿走对应 ...
- 批处理学习笔记11 - del命令和rd命令
这两个命令都是删除,所以放一块说了 del 删除文件 rd 删除目录(文件夹) ------------------------------------------------------------ ...
- FPGA Prototyping By Verilog Examples第五章 状态机FSM设计
上升沿检测电路之Moore型FSM // Listing 5.3module edge_detect_moore ( input wire clk, reset, input wire level, ...
- Linux minilogd占用内存过高及开机启动项修改
minilogd: 今天发现一台服务起的内存正常占用应该在70左右,但是内存占用却到了90%以上,用top查看发现minilogd占用了30%左右的内存,是不符合预期的,查看开机启动项并无minilo ...
- css margin塌陷问题
一.同级块级元素塌陷 html <h2> 同级块级元素塌陷 </h2> <div class="block1"> block1 </div ...
- Ajax的XMLHttpRequest对象的属性和方法总结
1.redayState属性: 当一个XMLHttpRequest对象被创建后,readyState属性别哦是当前对象正处于什么状态:0:未初始化状态:已经建立:1:准备发送状态:此时XMLHttpR ...