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子句被依次检查,第一个匹配异常类型的子句执行.当 ...
随机推荐
- Azure 怎么开通FTP
1. 需要在Azure Portal设置端口:21, 1035, 1036, 1037,1038,1039,1040 2. 需要内网放开端口:21, 1035, 1036, 1037,1038,103 ...
- 怎么修改Elasticsearch的对外ip 默认是本地IP 127.0.0.1
//修改C:\Program Files\elasticsearch-2.1.1\config\elasticsearch.yml: network.bind_host: 172.16.1.86 pa ...
- k8s的容器监测探针
大部分的应用程序我们在部署的时候都会适当的添加监控,对于运行载体容器则更应该如此.kubernetes提供了 liveness probes来检查我们的应用程序.它是由节点上的kubelet定期执行的 ...
- java Webservice(一)HttpClient远程调用
我们将Web Service发布在Tomcat或者其他应用服务器上后,有很多方法可以调用该Web Service,常用的有两种: 1.通过浏览器HTTP调用,返回规范的XML文件内容 2.通 ...
- [Jobdu] 题目1528:最长回文子串
题目描述: 回文串就是一个正读和反读都一样的字符串,比如“level”或者“noon”等等就是回文串.回文子串,顾名思义,即字符串中满足回文性质的子串.给出一个只由小写英文字符a,b,c...x,y, ...
- java playframework
刚学了java不久就让我们尝试架构,就选择了一个比較简单的架构 play framework直接上图 这里的执行环境是JDK1.7,我试了一下jdk1.8不行出问题了play使用的是play-1.2. ...
- 【Util】之——cookie
拿走即用 使用前引入文件:http://files.cnblogs.com/ccto/util-cookie.js 使用方法: //设置cookie CookieUtil.set("name ...
- nginx学习之epoll
https://blog.csdn.net/mmshixing/article/details/51848673 首先说一下传统的I/O多路复用select和poll,对比一下和epoll之间的区别: ...
- Linux RPM 命令参数使用详解 查看 rpm包依赖性
转载自:http://blog.csdn.net/deutschester/article/details/6309521 rpm 执行安装包 二进制包(Binary)以及源代码包(Source)两种 ...
- c++之——抽象基类
在一个虚函数的声明语句的分号前加上 =0:就可以将一个虚函数变成纯虚函数,其中,=0只能出现在类内部的虚函数声明语句处.纯虚函数只用声明,而不用定义,其存在就是为了提供接口,含有纯虚函数的类是抽象基类 ...