如何处理java代码的错误
我是 java 新手,正在尝试测试/改进我的程序。
它可以在我的计算机上运行,但不能在客户端上运行,因此我尝试进行错误处理,但不确定语法。
如何将 try/catch 放在 for 和 do while 循环以及 if 语句上。它会像其他命令一样进入它们内部吗?
for(int eight = 0; eight < 8; eight++)
{
message = in.readLine();
LOGGER.fatal(eight);
LOGGER.fatal(message);
if(message.contains("Content-Length"))
{
message.getChars(16, 20, size, 0); THIS LINE
}
}
这是我正在使用的一个例子。如何将 try/catch 添加到标记行。
或者你有更好的方法来处理异常吗?
I am new to java and and trying to test/improve my program.
it works on my computer but not on the clients so I and trying to do error handling but am not sure about the syntax.
How do you put try/catch on for and do while loops as well as if statements. would it just go inside them like any other command ?
for(int eight = 0; eight < 8; eight++)
{
message = in.readLine();
LOGGER.fatal(eight);
LOGGER.fatal(message);
if(message.contains("Content-Length"))
{
message.getChars(16, 20, size, 0); THIS LINE
}
}
this is a an example of what I am using. how do I add a try/catch to the marked line.
Or do you have a better way to handle the exceptions ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
如果您不想在发生异常时跳出循环,则只需将标记行封装在尝试/捕捉。
If you don't want to break out of the loop upon an exception you encapsulate only the marked line in the try / catch.
只需这样做即可。
记住:始终尝试在 catch 中使用特定的异常类而不是“Exception”,作为良好的编程实践。
Simply do this.
Remember : Always try to use specific exception class inside the catch instead of 'Exception' as a good programming practise.
try/catch 行的去向取决于您想要处理的具体内容。
您可能希望以相同的方式处理整个方法引发的所有异常(例如将更具可读性的版本传递给某些输出和/或将有意义的错误消息传递给用户) - 在这种情况下,您会执行类似的操作this:
或者,您可能想要处理特定行引发的异常(例如处理打开文件时引发的特定异常),在这种情况下,您只需用 try/catch 语句包围该行。
Where your try/catch lines go depends on what exactly you want to handle.
You may want to handle all exceptions thrown by an entire method in the same way (such as passing a more readable version to some output and/or passing a meaningful error message to the user) - in this case, you'd do something like this:
Alternatively, you may want to handle an exception thrown by a particular line (such as handling a specific exception thrown when opening a file), in which case you'd surround only that one line with your try/catch statements.
您的问题的简单答案是:
更好的答案是您需要修复异常的原因。我敢打赌,尝试提取内容长度的代码对输入行的“大小”字段中的字符数做出了无效的假设。更强大的方法是这样的:
显然,这会分配一个额外的字符串,但它的优点是它可以工作。
The simple answer to your question is:
A better answer is that you need to fix the cause of the exceptions. I bet it is the code that attempts to extract the content length is making invalid assumptions about the number of characters there are in the "size" field of an input line. A more robust approach is something like this:
Obviously, this allocates an extra String, but it has the advantage that IT WORKS.
您只需用
try
块包围可能抛出异常的行,并在catch
块中捕获抛出的异常。请参阅 Java 教程You simply surround the line(s) which might throw an Exception with a
try
-block and catch the thrown Exception in acatch
-Block. See the Java Tutorial