以下异常处理程序语句之间有什么区别? [英] What is the difference among the following exception handler statements?

查看:65
本文介绍了以下异常处理程序语句之间有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

嗨.
我是Java新手,我想知道使用和

Hi .
I am new in java, i am wondering about the difference between using and

throw and throws and try catch and finally

当我使用所有这些异常处理程序以及运行时异常和已检查的异常时

when i use all of these exception handlers and what are the run time exceptions and checked exceptions

推荐答案

请参阅 ^ ]很好地介绍了异常处理.
See here[^] for a good introduction on exception handling.


有两种处理异常的方法:

您可以抛出异常:

There are 2 ways to deal with exceptions:

you can throw an exception:

public int foo() throws Exception{
  // fancy code that needs Exception handling 
  // like reading a file or parsing a int value
}



在这里,您传回异常,而不是所需的int值.上面的方法必须处理异常,并可能将其传递或处理.

其他版本是直接捕获异常:



here you pass back the exception instead of the desired int-value. the method above has to deal with the exception and probably to pass it on or to deal with it.

Other version is to catch the exception direct:

public int foo() throws Exception{
  try{
    // fancy code that needs Exception handling 
    // like reading a file or parsing a int value
  }
  catch(Exception oException){
    oException.printStackTrace();
    return -1;
  }
}



在这种情况下,您会捕获异常并经常返回无效的int值,如-1.您可以在catch后面添加finally { }以确保无论try/catch是否失败(例如,关闭文件流,确保数据库不会失效)都可以执行某些操作.



in this case you catch the exception and often return a invalid int-value like -1. You can add a finally { } behind the catch to make sure certain operations are carried out no matter if the try/catch fails or not (e.g. closing file streams, making sure the database does not become invalid).


您要查询的信息可能会很容易在网络上找到自己: [
You are asking for info you may easily find yourself on the web: Google results for "Java exception handling tutorial"[^]


这篇关于以下异常处理程序语句之间有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆