有没有可能在方法内编写catch块并在try块中发生异常时从最后调用该块
例如:
try
{
int a=0,b=0;
a=b/0;
}
finally
{
callExceptions();
}
}
public static void callExceptions()
{
catch(Exception e)
{
System.out.println(e);
}
}
答案 0 :(得分:1)
catch
块必须在try
块之后。它不能孤独。
并且finally
块位于catch
之后。
您在catch
内单独编写了finally
。那没有道理。
最简单的解决方案是将异常作为参数传递给方法:
public static myMethod() {
try
{
int a=0,b=0;
a=b/0;
}
catch (Exception e)
{
callExceptions(e);
}
finally
{
// do what ever you want or remove this block
}
}
public static void callExceptions(Exception e)
{
System.out.println(e);
}
答案 1 :(得分:0)
使用try / catch / finally的方式
1.-当您想尝试使用某种方法时,如果一切顺利,将继续执行,否则将在catch块上引发一个异常。
start: [array([0, 1]), array([0, 1, 2]), array([0, 1, 2, 3])]
append an object
done!
finish: [array([505, 605]), array([10, 11, 12]), array([10, 11, 12, 13]), array([5])]
import time
from threading import Thread, Lock
import numpy as np
class Bucket(object):
def __init__(self, objects):
self.objects = objects
class Object(object):
def __init__(self, array):
self.array = array
class A(Thread):
def __init__(self, bucket):
Thread.__init__(self)
self.bucket = bucket
def run(self):
nloop = 0
locker = Lock()
n = 0
while n < 10:
with locker:
objects = self.bucket.objects[:] # makes a local copy of list each time
for i, obj in enumerate(objects):
with locker:
obj.array += 1
time.sleep(0.2)
n += 1
print 'n: ', n
print "done!"
return
objects = []
for i in range(3):
ob = Object(np.arange(i+2))
objects.append(ob)
bucket = Bucket(objects)
locker = Lock()
a = A(bucket)
print [o.array for o in bucket.objects]
a.start()
time.sleep(3)
with locker:
bucket.objects.append(Object(np.arange(1))) # abuse the bucket!
print 'append an object'
time.sleep(5)
print [o.array for o in bucket.objects]
2.-与第一个相同,但是添加finally块意味着,如果发生某些意外的异常,finally块将始终独立执行。
try {
// some method or logic that might throw some exception.
} catch (ExceptionType name) {
// catch the exception that was thrown.
}
3.- try和finally块用于确保关闭资源,而不管try语句是正常完成还是突然完成。例如:
try {
// some method or logic that might throw some exception.
} catch (ExceptionType name) {
// catch the exception that was thrown.
} finally {
// some logic after try or catch blocks.
}
Referencias (Official documentation JAVA for try/catch/finally blocks
)根据您的情况:
BufferedReader br = new BufferedReader(new FileReader(path));
try {
return br.readLine();
} finally {
if (br != null) br.close();
}
答案 2 :(得分:0)
这个评论的时间太长了,很抱歉,这不是您问题的直接答案(正如其他人指出的那样,这是不可能的)。假设您要尝试的是在一种地方定义一种处理异常逻辑的通用方法,那么Callable
可能是一种可行的方法。像下面这样的东西就足够了...尽管我不会评论其中的任何一个好主意...
static E callAndHandle(final Callable<E> callable) {
try {
return callable.call();
} catch (final Exception ex) {
System.out.println(ex);
return null;
}
}
static void tryIt() {
final String result = callAndHandle(() -> {
// Thing which might throw an Exception
return "ok";
});
// result == null => there was an error here...
}
不幸的是,Runnable
在签名中没有声明任何Exception
,因此如果您知道它始终需要为void
,并且您不喜欢return null;
或类似的黑客,您必须定义自己的接口才能传递。