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子句被依次检查,第一个匹配异常类型的子句执行.当 ...
随机推荐
- 关于VS中的调试信息输出
有时候一些项目的调试信息不方便输出到界面中,比如ASP.NET或者WPF之类的 可以使用Debug.WriteLine()等方法输出到"输出"窗口,不过"输出" ...
- Scala之集合Collection
概述 Scala的集合类能够从三个维度进行切分: 可变与不可变集合(Immutable and mutable collections) 静态与延迟载入集合 (Eager and delayed ev ...
- macbook中gcc替换为gnu gcc
macbook中gcc被定义为clang,而正统的gnu gcc却只能使用gcc-7(gcc 7版本),然而,如果修改/usr/bin的链接,还容易造成系统错误,因为mac的工具链和gcc(clang ...
- 判断js对象是否拥有某一个属性的js代码
js对象是否拥有某一个属性的判断方法有很多. 本文分享一个简单的方法,如下: <script> /** * 判断js对象是否具有某属性 * by www.jbxue.com */ var ...
- Hg(Mercurial)版本管理学习
1.关闭分支,首先切到你要关闭的分支 hg commit --close-branch -m. 2.仓库ip地址改变之后,重设仓库ip 找到.hg文件夹 - hgrc文件 - 记事本打开重设 3.推分 ...
- Synplify9.6.2破解(转帖)
Synplify9.6.2破解(转帖) 转载自:http://www.cnblogs.com/mark-sun/archive/2012/02/26/2368773.html Abstract本文 ...
- 【LeetCode-面试算法经典-Java实现】【136-Single Number(仅仅出现一次的数字)】
[136-Single Number(仅仅出现一次的数字)] [LeetCode-面试算法经典-Java实现][全部题目文件夹索引] 原题 Given an array of integers, ev ...
- express 设置node_env的环境变量
设置process.env.NODE_ENV的环境变量可以用以下2种方式: //在你的app.js文件中设置 process.env.NODE_ENV = 'development'; //在pack ...
- maven(5)------eclipse下maven常用命令打包
eclipse集成maven常用命令clean,install,一步完成项目清理和打包.在集成工具下使用maven 命令与命令窗口不同,需要将mvn省掉(比如:mvn clean,在工具中直接用cle ...
- uniqueIdentifier在ios7不支持后的替代方法
UIDevice的uniqueIdentifier方法在ios7就不支持了, 为了获得设备相关的唯一标识符, 参考了这里:https://github.com/Itayber/UIDevice-uni ...