标签: try-catch-finally

检查数组索引以避免越界异常

我对 Java 还很陌生,所以我有一种感觉,我在这里做的比我需要做的要多,并且希望就是否有更熟练的方法来解决这个问题提供任何建议。这是我想做的:

  1. 输出 Arraylist 中的最后一个值。

  2. 故意使用 system.out 插入越界索引值(本例中为索引 (4))

  3. 绕过不正确的值并提供最后一个有效的 Arraylist 值(我希望这是有意义的)。

我的程序运行良好(我稍后添加更多,因此最终将使用 userInput),但如果可能的话,我想在不使用 try/catch/finally 块(即检查索引长度)的情况下执行此操作。谢谢大家!

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;

public class Ex02 {

public static void main(String[] args) throws IOException {

    BufferedReader userInput = new BufferedReader(new InputStreamReader(
            System.in));

    try {
        ArrayList<String> myArr = new ArrayList<String>();
        myArr.add("Zero");
        myArr.add("One");
        myArr.add("Two");
        myArr.add("Three");
        System.out.println(myArr.get(4));

        System.out.print("This program is not currently setup to accept user input. The last       printed string in this array is: ");

    } catch (Exception e) { …
Run Code Online (Sandbox Code Playgroud)

arraylist try-catch-finally indexoutofboundsexception

1
推荐指数
1
解决办法
4571
查看次数

Java try catch 最后似乎毫无意义

这是一个非常愚蠢的问题,但我不明白 catch 和 finally 的组合使用。据我所知,无论是否引发异常,catch 块之后的代码都会执行,那么为什么要使用

try
{
    doSomething();
}
catch(Exception e)
{
    e.printStackTrace();
}
finally
{
    doSomethingInFinally();
}
Run Code Online (Sandbox Code Playgroud)

代替

try
{
    doSomething();
}
catch(Exception e)
{
    e.printStackTrace();
}

doSomethingInFinally();
Run Code Online (Sandbox Code Playgroud)

?我总是看到人们使用第一种模式,但我认为这是额外的代码。

java try-catch-finally

1
推荐指数
1
解决办法
570
查看次数

如何在C#中将程序流显式传递给finally块?

在Delphi中,我可以这样做:

try
  if not DoSomething then
    Exit;
  if not DoSomething2 then
    Exit;
  if not DoSomething3 then
    Exit;

finally
  DoSomethingElse;
end;
Run Code Online (Sandbox Code Playgroud)

在其他方法中,如果方法DoSomething结果为假,则程序流被转移到finally块,DoSomething2并且DoSomething3不执行.

如何在C#中实现这种行为?

提前致谢.

Edit1: 以下示例无法在VS 2008中编译

编辑2:对不起,我要快速忘记退货声明;

XElement OrderStatus(q_order_status Request)
{
  XElement Response;
  try
  { 
    if (DoSomething() != 0 )
    {
      return;
    }
  }
  catch(Exception e)
  {
    // catch some errors and eventually pass the e.Message to the Response
  }
  finally
  {
    Response =  new XElement("SomeTag", "SomeResponse");
  }
  return Response;
}
Run Code Online (Sandbox Code Playgroud)

Edit3: 经过测试,似乎最简单的方法是在结果 …

c# delphi try-catch-finally

0
推荐指数
1
解决办法
1901
查看次数

Java:关于finally块的假设性问题

如果在finally块中抛出错误会发生什么?它是否在一个相应的catch子句中处理?

java error-handling try-catch-finally

0
推荐指数
1
解决办法
488
查看次数

使用Try-Catch-Finally来处理算术异常

我想尝试两种不同的东西(两者都有很大的失败可能性),因此我想使用"finally"语句运行"安全",以防前两次尝试失败.

请看以下示例(这不是我在项目中使用的代码!).

int zero = 0;
int one = 1;

try
{
    // Throws ' cannot divide by zero ' error
    int error = one / zero;
}

catch
{
    // Throws error again of course
    int somenum = one / zero;
}

finally 
{
    MessageBox.Show("I can never make it here ..."); 
}
Run Code Online (Sandbox Code Playgroud)

所以,我希望我的程序能够执行以下操作:

  1. 尝试除以零
  2. 如果步骤#1 失败,我希望'catch'语句运行它的代码(在这个例子中它应该再次失败).
  3. 如果步骤#1和#2都失败了,我希望我的程序在'finally'语句中显示MessageBox.

我甚至接近这个吗?

c# error-handling try-catch-finally

0
推荐指数
1
解决办法
4282
查看次数

为什么我的计数器变量在多线程场景中不会回到0?

我正在构建一个Windows服务基类来管理轮询任何待处理任务的计划表并运行它们.

Windows服务正在使用它System.Timers.Timer来启动计划的表轮询.

ThreadPool.SetMaxThread在初始化定时器之前将其设置为10.

    protected override void OnStart(string[] args)
    {
        ThreadPool.SetMaxThreads(10, 10);

        this._Timer = new System.Timers.Timer();
        this._Timer.Elapsed += new ElapsedEventHandler(PollWrapper);
        this._Timer.Interval = 100;
        this._Timer.Enabled = true;
    }
Run Code Online (Sandbox Code Playgroud)

计时器调用的委托方法保留正在运行的线程的计数,以便可以在OnStop()方法中使用它来等待每个线程在处置服务之前完成.

    private void PollWrapper(object sender, ElapsedEventArgs e)
    {
        numberOfRunningThreads++;

        try
        {
            this.Poll(sender, e);
        }
        catch (Exception exception)
        {
            //some error logging here
        }
        finally
        {
            numberOfRunningThreads--;
        }
    }




    protected override void OnStop()
    {
        this._Timer.Enabled = false;

        while (numberOfRunningThreads > 0)
        {
            this.RequestAdditionalTime(1000);
            Thread.Sleep(1000);
        }
    }
Run Code Online (Sandbox Code Playgroud)

通常,当我尝试从Windows服务管理控制台停止服务时,服务不会停止.如果我调试它并向OnStop()方法添加断点,我可以看到它不是因为numberOfRunningThreads卡在大于0的数字上(通常远大于10!).没有任务正在运行,它永远保留在该号码上!

首先,我不明白这个数字怎么可能大于10,尽管它ThreadPool.SetMaxThreads应该限制​​在10?

其次,即使我没有设置最大线程数,我也期望PollWrapper的finally块最终将计数恢复为0.如果计数器保持大于0,则只能用finally块来解释执行,对吧!?怎么可能? …

c# windows-services timer try-catch-finally

0
推荐指数
2
解决办法
203
查看次数

最后阻止表现不同

我有这样的条件

String str = null;

try{
  ...
  str = "condition2";
}catch (ApplicationException ae) {
  str = "condition3";
}catch (IllegalStateException ise) {
  str = "condition3";
}catch (Exception e) {
  str = "condition3";
}

if(str == null){
  str = "none";
}
Run Code Online (Sandbox Code Playgroud)

现在我想总结一下str = "condition3";.最后,块总是运行,以至于无法满足我的需求.还有什么可以做的.

java finally try-catch try-catch-finally

0
推荐指数
1
解决办法
176
查看次数

当我尝试在finally块中关闭BufferedReader时,为什么eclipse会抱怨?

这是我的代码:

public static String readFile()
    {

        BufferedReader br = null;
        String line;
        String dump="";

        try
        {
            br = new BufferedReader(new FileReader("dbDumpTest.txt"));
        }
        catch (FileNotFoundException fnfex)
        {
            System.out.println(fnfex.getMessage());
            System.exit(0);
        }

        try
        {
            while( (line = br.readLine()) != null)
            {
                dump += line + "\r\n";
            }
        }
        catch (IOException e)
        {
            System.out.println(e.getMessage() + " Error reading file");
        }
        finally
        {
            br.close();
        }
        return dump;
Run Code Online (Sandbox Code Playgroud)

因此eclipse正在抱怨由此引发的未处理的IO异常 br.close();

为什么会导致IO异常?

我的第二个问题是为什么eclipse不会抱怨以下代码:

InputStream is = null; 
      InputStreamReader isr = null;
      BufferedReader br = null;

      try{
         // …
Run Code Online (Sandbox Code Playgroud)

java eclipse exception try-catch-finally bufferedreader

0
推荐指数
1
解决办法
533
查看次数

当我们可以关闭文件和所有catch块时,finally块的需要是什么

finally当我们可以关闭文件和所有块时,需要阻止什么catch.无论我们在finally块中关闭或清除什么,都可以在块中完成catch.请告诉我,如果我错了.

java exception-handling exception try-catch-finally

0
推荐指数
1
解决办法
370
查看次数

为什么return在最终块中不遵守变量的值?

finally总是最后执行,因此该语句x = 3应该最后执行。但是,运行此代码时,返回的值为2。

为什么?

class Test {
    public static void main (String[] args) {
        System.out.println(fina());
    }

    public static int fina()
    {
        int x = 0;
        try {
            x = 1;
            int a = 10/0;
        }
        catch (Exception e)
        {
            x = 2;
            return x;
        }
        finally
        {
            x = 3;
        }
        return x;
    }
}
Run Code Online (Sandbox Code Playgroud)

java exception try-catch-finally

0
推荐指数
1
解决办法
74
查看次数