`
qdpurple
  • 浏览: 272974 次
  • 性别: Icon_minigender_1
  • 来自: 北京
社区版块
存档分类
最新评论

平台异常2 - try/catch or throws

阅读更多

在处理抛出异常的方法时,我们可以采用try/catch进行捕捉 或者使用throws抛出, 但具体怎么使用, 什么时候进行try/catch,什么时候进行throws? 现通过代码简要总结.

实验1 :使用try/catch

 在main方法中对methord1()抛出的异常进行捕捉 

import java.io.File;
import java.io.IOException;

public class ExceptionTest {

	public static void main(String[] args) {
		try {
			methord1();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		methord2();
	}
	private static void methord1() throws IOException {
		// TODO Auto-generated method stub
		System.out.println("methord1 ");
		File f = new File("");
		f.createNewFile();
		
		System.out.println("methord1111 ");
	}
	private static void methord2() {
		// TODO Auto-generated method stub
		System.out.println("methord2 ");
	}
}

,结果为:

methord1 
java.io.IOException: 系统找不到指定的路径。
	at java.io.WinNTFileSystem.createFileExclusively(Native Method)
	at java.io.File.createNewFile(File.java:850)
	at com.bryant.test.ExceptionTest.methord1(ExceptionTest.java:21)
	at com.bryant.test.ExceptionTest.main(ExceptionTest.java:10)
methord2 

 methord2 方法也执行.

 

实验2.使用throws

修改main方法为throws methord1()抛出的异常:

public static void main(String[] args) throws IOException {
		
		methord1();
		methord2();
	}

 

结果为:

methord1 
Exception in thread "main" java.io.IOException: 系统找不到指定的路径。
	at java.io.WinNTFileSystem.createFileExclusively(Native Method)
	at java.io.File.createNewFile(File.java:850)
	at com.bryant.test.ExceptionTest.methord1(ExceptionTest.java:17)
	at com.bryant.test.ExceptionTest.main(ExceptionTest.java:10)

 方法methord2 没有执行.

由此总结:

当出现的异常使程序后面无法执行时,抛出异常,结束程序.使用throws
当程序出现异常,不影响后续操作时,捕捉异常,后续程序将继续执行.使用try/catch

 

 

 

 

分享到:
评论
13 楼 Loudyn 2011-02-16  
白糖_ 写道
异常分两类:运行时异常(RuntimeException)和非运行时异常,运行时异常是不需要刻意去捕获的(比如空指针,溢出等),而非运行时异常在java里明确需要你处理(比如IO异常等),我们在编码过程中其实不需要一直抛异常,只有在遇到非运行时异常的时候才需要你去处理。
你直接try{}catch (IOException e) {   
             e.printStackTrace(); }
其实不大明智,你在这里catch了IO异常,但是并未处理它,我建议你通过throw e或者throw new 自定义异常(**)去处理它


加多一句,编码过程也不需要一直try catch
12 楼 qdpurple 2011-02-16  
谢谢 我会努力地
11 楼 qdpurple 2011-02-16  
白糖_ 写道
异常分两类:运行时异常(RuntimeException)和非运行时异常,运行时异常是不需要刻意去捕获的(比如空指针,溢出等),而非运行时异常在java里明确需要你处理(比如IO异常等),我们在编码过程中其实不需要一直抛异常,只有在遇到非运行时异常的时候才需要你去处理。
你直接try{}catch (IOException e) {   
             e.printStackTrace(); }
其实不大明智,你在这里catch了IO异常,但是并未处理它,我建议你通过throw e或者throw new 自定义异常(**)去处理它


谢谢.
我理解了你意思 : 平时在编码时,看到Checked Exception就自然是用了try catch捕捉,在catch中只写打印堆栈信息. 没使用过throw ,现在听你的解释,明白了. 以后再捕捉异常时,如果不能处理就尽量抛出.
10 楼 白糖_ 2011-02-16  
异常分两类:运行时异常(RuntimeException)和非运行时异常,运行时异常是不需要刻意去捕获的(比如空指针,溢出等),而非运行时异常在java里明确需要你处理(比如IO异常等),我们在编码过程中其实不需要一直抛异常,只有在遇到非运行时异常的时候才需要你去处理。
你直接try{}catch (IOException e) {   
             e.printStackTrace(); }
其实不大明智,你在这里catch了IO异常,但是并未处理它,我建议你通过throw e或者throw new 自定义异常(**)去处理它

9 楼 whaosoft 2011-02-15  
慢慢来 学技术就得脸大 怎么可能每次都对呢
8 楼 qdpurple 2011-02-15  
aflyer 写道
我无语了!
        try { 
            methord1(); 
        } catch (IOException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        }

谢谢指教.
我随手写的代码,只是想说明一下问题,代码命名让你见笑了
7 楼 qdpurple 2011-02-15  
freish 写道
新手贴???

是, 我刚接触实际的项目开发. 请多指教.
6 楼 qdpurple 2011-02-15  
smilebug 写道
这个……本来就是两个东西一个抛出一个捕获

谢谢你的回复. 我想说明的是何时使用抛出 ,何时捕获.
5 楼 qdpurple 2011-02-15  
elliotann 写道
throws抛给上一层处理,try/catch捕获,是出现异常时在catch中做些处理,并不是中止程序,也没默认return;

谢谢你的回复. 我表述有问题 ,应该是当使用throw 时,程序跳出本方法执行,throw后面的代码讲不执行.
你说的 return 指什么?
4 楼 aflyer 2011-02-15  
我无语了!
        try { 
            methord1(); 
        } catch (IOException e) { 
            // TODO Auto-generated catch block 
            e.printStackTrace(); 
        }
3 楼 freish 2011-02-15  
新手贴???
2 楼 elliotann 2011-02-15  
throws抛给上一层处理,try/catch捕获,是出现异常时在catch中做些处理,并不是中止程序,也没默认return;
1 楼 smilebug 2011-02-14  
这个……本来就是两个东西一个抛出一个捕获

相关推荐

    带注释的Bootstrap.java

    throws Exception { //CatalinaProperties解析$CATALINA_HOME\conf\catalina.properties, //并将catalina.properties内的属性存为系统属性 //catalina.properties内common.loader="${catalina.base}/lib", ...

    Java网络编程-Socket-文件传输小案例

    public ReveiceThread(SocketChannel channel) throws Exception { this.r_channel = channel; this.r_channel.configureBlocking(false); } public void run() { try { Selector selector = Selector.open...

    Servlet查询数据库案例--Query(java源码)

    * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied. * You may study, use, and modify it for any non-commercial purpose. * You may distribute it non-commercially as long as you...

    我的网页作品

    // NOTE : new ActiveXObject(strFoo) throws an exception if strFoo isn't in the registry try { // version will be set for 7.X or greater players axo = new ActiveXObject("ShockwaveFlash.Shockwave...

    数据库工具类DatabaseUtil.java

    * <code>UPDATE</code>, or <code>DELETE</code> statement or an SQL * statement that returns nothing, such as an SQL DDL statement. 执行给定的 SQL * 语句, 这些语句可能是 INSERT, UPDATE 或者 DELETE ...

    File_实用案例_实现文件拷贝_FileCopy.java

    * It is provided AS-IS, WITHOUT ANY WARRANTY either expressed or implied. * You may study, use, and modify it for any non-commercial purpose. * You may distribute it non-commercially as long as you...

    swing文件拖拽

    new DropTarget(this, DnDConstants.ACTION_COPY_OR_MOVE, this); // Set up a hover timer, so that a node will be automatically expanded // or collapsed // if the user lingers on it for more than a ...

    springmybatis

    DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN" "http://mybatis.org/dtd/mybatis-3-config.dtd"> <typeAliases> <typeAlias alias="User" type="com.yihaomen.mybatis.model.User"/> </...

    SMSLib(短信猫)的开发与配置jar包合集

    public void doIt() throws Exception { Service srv; OutboundMessage msg; OutboundNotification outboundNotification = new OutboundNotification(); System.out.println("Example: Send message from a ...

    Java 语言基础 —— 非常符合中国人习惯的Java基础教程手册

    (2) 类名是由程序员自己定义的 Java 标识符,每个类说明必须有 class 和类名。 (3) 类说明修饰符包括:  abstract 说明一个类为抽象类,抽象类是指不能直接实例化对象的类。  final 说明一个类为最终类,即...

    android 串口驱动

    * Do not remove or rename the field mFd: it is used by native method close(); */ private FileDescriptor mFd; private FileInputStream mFileInputStream; private FileOutputStream mFileOutputStream...

    Google C++ Style Guide(Google C++编程规范)高清PDF

    Another useful rule of thumb: it's typically not cost effective to inline functions with loops or switch statements (unless, in the common case, the loop or switch statement is never executed)....

    整理后java开发全套达内学习笔记(含练习)

    throw (关键字) throws (关键字) [θrәu] 抛出(异常) transient (关键字) 瞬变;临时的['trænziәnt]'(可序列化) valid 正确的,有效的 ['vælid] variable n.变量 a.可变的['vєәriәbl] volatile (关键字) 不...

    socket编程集萃

     //transfer location change Single User or Multi User  MultiUser mu=new MultiUser(server.accept());  mu.start();  }  }  }  我的类直接从Thread类继承了下来.并且通过构造函数传递引用和客户...

Global site tag (gtag.js) - Google Analytics