我刚刚在我们的一个Java库中遇到了一个隐藏的gem:
for(Widget w : widgets) {
if(shouldDoStuff()) {
try{
// Do stuff to w.
} catch(Exception e){
throw new RuntimeException("Couldn't do stuff.");
} finally{
// Compiler warning: finally block does not complete normally
continue;
}
}
}
Run Code Online (Sandbox Code Playgroud)
我知道这finally胜过一切,但我想知道两件事:
catch条款不执行呢?异常是否被抛出?首先发生什么:抛出的异常或continue声明?我发现了这个非常相似的问题,但是接受的答案只是声明异常将被突然抛出,我不确定这意味着什么.另外,它并没有真正帮助我理解我上面提到的关于将要发生的事件顺序的第一个问题.
我正在自学 C#,我要学习 try、catch 和 finally。我正在使用的这本书讨论了 finally 块如何运行,而不管 try 块是否成功。但是,即使不在 finally 中,写在 catch 块之外的代码也不会运行吗?如果是这样,最后的意义是什么?这是本书提供的示例程序:
class myAppClass
{
public static void Main()
{
int[] myArray = new int[5];
try
{
for (int ctr = 0; ctr <10; ctr++)
{
myArray[ctr] = ctr;
}
}
catch
{
Console.WriteLine("Exception caught");
}
finally
{
Console.WriteLine("Done with exception handling");
}
Console.WriteLine("End of Program");
Console.ReadLine();
}
}
Run Code Online (Sandbox Code Playgroud) 我想将java异常处理翻译成c++,而不使用RAII。
问题主要与finally块有关。
我发现一篇论文使用以下方法:
“一个困难是,finally 子句必须在每次退出 try 块之前执行。一般 try 块的潜在退出数量惊人:正常退出、抛出异常、return 语句、break 语句、 continue 语句,或者未能捕获异常。finally 子句必须在这些语句之前执行(如果它们用在 try 块或 catch 块中)。例如,下面的 Java 代码显示了大多数从尝试块:
try {
switch (x) {
case 0: continue next;
case 1: break out;
case 2: throw new TException();
case 3: return(0);
}
} catch (Error e) {
throw(e);
} finally {
System.out.println("finally");
}
Run Code Online (Sandbox Code Playgroud)
我们的解决方案是简单地在必须执行的所有地方复制finally 块的文本。如果finally 块的大小很大,这可能表明Java 程序员可能希望将其设为一个方法,以便最大限度地减少C++ 中的代码重复。
以下 C++ 代码显示了如何为 try 块的所有退出复制 finally 块:”
try
{
switch(x)
{
case 0:
/* finally clause, continue from try block */
java_lang_System::out->println(_j_toString("finally")); …Run Code Online (Sandbox Code Playgroud) 这是代码
while True:
try:
age = int(input("Enter your age"))
except ValueError:
print("Enter the age in integer")
continue
except ZeroDivisionError: #when trying to divide the age for an age groups
print("Age cannot be zero")
continue
else:
print("thank you!!")
break
finally:
print("ok! I am finally done")
Run Code Online (Sandbox Code Playgroud)
在输入中,对于年龄,我给出一个字符串(例如:wefervrsvr),因此它必须经过ValueErrorexcept 块中的 ,该块具有print函数和 thencontinue语句,该语句使程序的控制到达循环的顶部,因此它再次要求输入来自我们,但我在这里不明白的是,为什么最终会在控制跳转到顶部的 try 块之前执行,正如我在输出中看到的那样。
我用来Files.walk()从目录中获取一些文件,但我从 Sonarqube 和 Sonarlint 代码分析中收到有关阻止程序错误的警告
连接、流、文件和其他实现 Closeable 接口或其超级接口 AutoCloseable 的类在使用后需要关闭。此外,该关闭调用必须在finally 块中进行,否则异常可能会导致调用无法进行。最好,当类实现 AutoCloseable 时,应使用“try-with-resources”模式创建资源并将自动关闭。
这是代码:
Files.walk(Paths.get(ifRecordsPath))
.filter(Files::isDirectory)
.map(ifRecordsCollector)
.map(ifRecordStreamAccumulator)
.forEach(ifRecordCollection::addAll);
return ifRecordCollection;
Run Code Online (Sandbox Code Playgroud)
我读了这篇文章,几乎遇到了问题,但我不知道如何准确地将流停止在正确的位置。当我添加finally块时,它仍然给出相同的错误
try {
Files.walk(Paths.get(ifRecordsPath))
.filter(Files::isDirectory)
.map(ifRecordsCollector)
.map(ifRecordStreamAccumulator)
.forEach(ifRecordCollection::addAll);
} finally {
Files.walk(Paths.get(ifRecordsPath)).close();
}
Run Code Online (Sandbox Code Playgroud)
我该如何解决这个问题?
java spring try-catch-finally try-with-resources java-stream
我有一个try... catch... finally块,其catch重新抛出异常:
try
{
startBombCountdownAndRunAsFastAsYouCan();
}
catch (BombExplodedOnYourFaceException ex)
{
displayMessage("Hahaha! It blew up on your face!");
throw ex;
}
finally
{
cleanFloor();
}
displayMessage("Wow, you pulled it off!");
Run Code Online (Sandbox Code Playgroud)
在这个例子中,我需要cleanFloor()执行它,无论是否抛出异常.所以,问题是:该finally条款始终执行,无论异常是否被相应的重新抛出catch的条款?
当我编译下面的代码时,它显示错误"找不到符号变量"但是如果我在finally块中注释代码,我能够成功编译.
请指教.
public static int writeFile (String p_file_path, String p_data) throws Exception
{
try {
FileWriter outFile = new FileWriter(p_file_path,true);
PrintWriter out = new PrintWriter(outFile);
out.println(p_data);
} catch (Exception e) {
} finally {
out.close();
}
return SUCCESS;
}
Run Code Online (Sandbox Code Playgroud) 一旦我执行下面的代码,媒体播放60秒,我的应用程序关闭,出现错误"不幸的是,YourAPP已经停止." .如果我删除"bv.setImageResource(R.drawable.play);" 在最后阻止,该应用程序完美.
bv.setImageResource(R.drawable.play)在finally块上有什么问题?
这是我的代码
bv = (ImageButton) findViewById(R.id.imageButton1);
private void mpsleep() {
mp.start();
Thread timer= new Thread(){
public void run(){
try{
for (i =1;i<60;i++){
sleep(1000);//1 second pause
}
}catch(Exception e){
e.printStackTrace();
}finally{
mp.pause();
mp.seekTo(0);
bv.setImageResource(R.drawable.play);
}
}
};
timer.start();
}
Run Code Online (Sandbox Code Playgroud)
logcat的
03-06 11:03:39.743: V/MediaPlayer(31802): message received msg=4, ext1=0, ext2=0
03-06 11:03:39.743: V/MediaPlayer(31802): Received seek complete
03-06 11:03:39.743: V/MediaPlayer(31802): All seeks complete - return to regularly scheduled program
03-06 11:03:39.743: V/MediaPlayer(31802): callback application
03-06 11:03:39.743: V/MediaPlayer(31802): back from callback
03-06 …Run Code Online (Sandbox Code Playgroud) 我知道创建一个没有finally块的try-catch段是有效的.因此,在使用此代码进行黑客攻击时,我无法弄清楚java逻辑(例如规则,理论)迫使我在这段代码中包含finally块 - 以及为什么finally块必须在其中包含return语句.换句话说,如果我完全删除finally块我收到一个错误,如果我用finally其他东西替换finally块中的return语句(例如System.out.printl(''foo")),我仍然收到一个错误我坚持要包含一个return语句.再次,这里编写的代码编译并运行正常.我只是想了解try-catch-finally构造背后的一些理论(ps我明白它的全部是关于"异常处理"......但我的问题更多的是关于代码流和返回语句).
class foo {
int getInt() {
try {
String[] students = {"student1", "student2"};
System.out.println(students[4]);
}
catch (Exception e) {
return 10;
}
finally {
return 20;
}
}
public static void main(String args[]) {
foo classSize = new foo();
System.out.println(classSize.getInt());
}
}
Run Code Online (Sandbox Code Playgroud) 我是否认为以下代码块是正确的:
try
{
Screen->Cursor = crHourGlass;
try
{
throw Exception("error!");
}
catch(Exception& e)
{
Application->MessageBox(UnicodeString(e.Message).c_str(), L"Error", MB_OK);
}
}
__finally
{
Screen->Cursor = crDefault;
}
Run Code Online (Sandbox Code Playgroud)
实际上是否与此相同,并且__finally在这里毫无用处,因为在两种情况下,无论如何都将执行Screen-> Cursor = crDefault?
Screen->Cursor = crHourGlass;
try
{
throw Exception("error!");
}
catch(Exception& e)
{
Application->MessageBox(UnicodeString(e.Message).c_str(), L"Error", MB_OK);
}
Screen->Cursor = crDefault;
Run Code Online (Sandbox Code Playgroud)