在Java 7中,该功能被添加到(通过getSuppressed())获取从try-with-resources语句的隐式finally块中抛出的异常.
似乎还没有一种方法(我知道)做相反的事情 - 当有一个显式的finally块并抛出异常时,屏蔽抛出的异常和try/catch中的异常.
为什么Java不提供通过类似机制获取这些隐藏/丢失异常的功能getSuppressed()?
看起来这个功能的实现与在getSuppressed()链接异常中使用的功能类似,并且所提供的好处非常有用,但它仍然被排除在每个版本之外.
通过类似于的方法调用,程序员可以使用这些屏蔽异常的危险是什么getSuppressed()?
(如果这个功能已经存在,请提前道歉,我只是无能为力.)
我读了很多关于java中的try/catch/finally过程的页面,但我没有成功地ClassNotFoundException在我的代码中捕获。我使用for 循环打开并以 rdfxml 格式保存我作为参数给出的目录中的每个文件。我想要的是,当我执行代码时,我得到 e.getmessage() 并且循环继续处理下一个文件。
问题是我的脚本工作得很好,但当发生 ClassNotFoundException 时我没有收到 e.getmessage() 。
@SuppressWarnings("finally")
public static void main(String[] args) {
File dir = new File(args[0]);
File[] directoryListing = dir.listFiles();
if (directoryListing != null) {
for (File owlFile : directoryListing){
String name = owlFile.getName();
try {
translateOwlToRdfXml(owlFile,name);
}
catch (OWLOntologyCreationException|OWLOntologyStorageException|ClassNotFoundException e) {
System.out.println(name + " has not been saved into RDF/XML;");
System.out.println(e.getMessage());
}
finally {
continue;
}
}
}
}
static void translateOwlToRdfXml(File owlFile, String name) throws OWLOntologyCreationException, OWLOntologyStorageException, …Run Code Online (Sandbox Code Playgroud) 我正在将一些C#代码转换为Java,它包含该using语句.我应该如何在Java中复制此功能?我要使用try,catch,finally块,但我想我会跟你们先检查.
try
{
try
{
throw new Exception("From Try");
}
catch
{
throw new Exception("From Catch");
}
finally
{
throw new Exception("From Finally");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
Run Code Online (Sandbox Code Playgroud)
上面代码的输出是:From Finally.
为什么不From Catch呢?
-要么-
我怎样才能从外部捕获和记录两个例外?
看起来我还没有处理异常处理的问题.我不知所措:(以下代码有时会返回此错误:
File "applications/pingback/modules/plugin_h_pingback.py", line 190, in ping
db(table.id==id_).update(status=status)
UnboundLocalError: local variable 'status' referenced before assignment
Run Code Online (Sandbox Code Playgroud)
我希望status总是被分配一个值.可能是抛出了一些其他异常(也许是在内部try)并且finally模糊了它?
...
try:
server_url = self._get_pingback_server(target)
except PingbackClientError, e:
status = e.message
else:
try:
server = xmlrpclib.ServerProxy(server_url)
status = server.pingback.ping(self.source, target)
except xmlrpclib.Fault, e:
status = e
finally:
db(table.id==id_).update(status=status) # <-- UnboundLocalError
...
Run Code Online (Sandbox Code Playgroud)
谢谢,HC
我有一些看起来像这样的代码:
foreach(var obj in collection)
{
try
{
// WriteToFile returns the name of the written file
string filename = WriteToFile(obj);
SendFileToExternalAPI(filename);
}
catch ( ArbitraryType1Exception e )
{
LogError(e);
continue;
}
...
catch ( ArbitaryTypeNException e )
{
LogError(e);
continue;
}
finally
{
try
{
File.Delete(filename);
}
catch (Exception e)
{
LogError(e);
}
}
}
Run Code Online (Sandbox Code Playgroud)
目标是尝试为集合中的每个对象写出一个临时文件,尝试将该文件加载到需要文件名的外部API中,然后在完成后清理临时文件.如果在将文件写入磁盘或将其加载到外部API时发生错误,我只想记录错误并转到下一个对象; 我不能问用户该做什么.
当你在catch处理程序中有continue语句时,我有点不确定finally块的时序如何工作.无论是否在try块中抛出异常,此代码是否会(尝试)删除正确的文件?或者,在finally块运行之前,catch语句中的continue是否生效?
说(可能在一个单独的线程上)我正在运行一些方法ClassA.foobar().在这个方法里面是一个尝试,(可能是捕获),最后阻止.
现在,如果执行仍在try-block(或catch-block)中间时,对此ClassA对象(或此线程)的最后一次引用会丢失,那么此对象(/ thread)是否可以在我获取之前进行垃圾回收到了最后一块?换句话说:即使没有对内存中剩余的对象(/ thread)的强引用,finally块仍然可以保证运行吗?
(我不知道GC如何处理孤立的活线程.)
虚拟的例子:
[Some context]
{
ClassA classA = new ClassA();
//Point is this instance and a reference to it exists
class ClassA
{
public void foobar()
{
try
{
classA = null;
//Point is that the last reference to this instance is lost,
//and that this happens at this point in foobar() execution.
//The actual location of this line of code is irrelevant.
}
finally
{
//some important stuff here!
}
}
}
}
Run Code Online (Sandbox Code Playgroud) java garbage-collection finally thread-safety try-catch-finally
有三种情况需要考虑:
情况1:
public class Test {
public static void main(String[] args) {
System.out.println(1);
System.out.println(2);
return;
System.out.println(3);
}
}
Run Code Online (Sandbox Code Playgroud)
案例2:
public class Test {
public static void main(String[] args) {
try{
System.out.println(1);
return;
}finally{
System.out.println(2);
}
System.out.println(3);
}
}
Run Code Online (Sandbox Code Playgroud)
案例3:
public class Test {
public static void main(String[] args) {
try{
System.out.println(1);
return;
}catch(Exception e){
System.out.println(2);
}
System.out.println(3);
}
}
Run Code Online (Sandbox Code Playgroud)
我理解,如果1语句System.out.println(3)无法访问,这就是为什么它是编译器错误,但为什么编译器在情况3中没有显示任何错误.
另请注意,在案例2中甚至是编译器错误.
当我尝试在Java中执行以下函数时:
public static int myfunc (int x) {
try {
return x;
} finally {
x++;
}
}
public static void main (String args[]) {
int y=5,z;
z = myfunc(y);
System.out.println(z);
}
Run Code Online (Sandbox Code Playgroud)
控制台上打印的输出为5,可以预期打印6.知道为什么吗?
我正在尝试try-catch-finally,这样如果mainLog成功创建,但在此之后抛出异常,它将被正确处理掉.但是,如果未成功创建mainLog 并且存在mainLog.Dipose()方法调用,则会出现另一个异常.通常情况下,我会做一个if语句,但DocX.Create()不会返回bool所以我不知道该怎么做.谢谢.
public static string Check_If_Main_Log_Exists_Silent()
{
DocX mainLog;
string fileName = DateTime.Now.ToString("MM-dd-yy") + ".docx";
string filePath = @"D:\Data\Main_Logs\";
string totalFilePath = filePath + fileName;
if (File.Exists(totalFilePath))
{
return totalFilePath;
}
else if (Directory.Exists(filePath))
{
try
{
mainLog = DocX.Create(totalFilePath);
mainLog.Save();
mainLog.Dispose();
}
catch (Exception ex)
{
MessageBox.Show("The directory exists but the log does not exist and could not be created. " + ex.Message, "Log file error");
return null;
}
}
else …Run Code Online (Sandbox Code Playgroud)