我对 Java 还很陌生,所以我有一种感觉,我在这里做的比我需要做的要多,并且希望就是否有更熟练的方法来解决这个问题提供任何建议。这是我想做的:
输出 Arraylist 中的最后一个值。
故意使用 system.out 插入越界索引值(本例中为索引 (4))
绕过不正确的值并提供最后一个有效的 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) 这是一个非常愚蠢的问题,但我不明白 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)
?我总是看到人们使用第一种模式,但我认为这是额外的代码。
在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: 经过测试,似乎最简单的方法是在结果 …
如果在finally块中抛出错误会发生什么?它是否在一个相应的catch子句中处理?
我想尝试两种不同的东西(两者都有很大的失败可能性),因此我想使用"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)
所以,我希望我的程序能够执行以下操作:
我甚至接近这个吗?
我正在构建一个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块来解释执行,对吧!?怎么可能? …
我有这样的条件
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";.最后,块总是运行,以至于无法满足我的需求.还有什么可以做的.
这是我的代码:
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) finally当我们可以关闭文件和所有块时,需要阻止什么catch.无论我们在finally块中关闭或清除什么,都可以在块中完成catch.请告诉我,如果我错了.
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)