有没有办法可以绕过Java中的错误信息? 如果我收到错误怎么办,但是没有可行的方法来改变我的程序?如果我怀疑我可能会从一段代码中收到错误,但我不知道何时或是否会发生错误怎么办?很多时候我不得不在我的代码中放一些东西,但却产生了一个错误。例如,使用parseFloat()将字符串转换为float。
无论如何要做到这一点?
答案 0 :(得分:2)
我认为您需要try...catch
声明。
try {
// parse your float here
} catch (NumberFormatException ex) { // parsing a float might throw a NumberFormatException
// code in here will be executed if a NumberFormatException occurs
}
答案 1 :(得分:2)
是您可以用Java处理运行时错误。
异常处理
有两种方法可以处理异常。
当程序代码中发生异常时,只需将其抛出并忽略异常发生(即将方法声明为Iterator it = dayOfWeek.entrySet().iterator();
while (it.hasNext()) {
Map.Entry pair = (Map.Entry)it.next();
System.out.println(pair.getKey() + " = " + pair.getValue());
if (pair.getValue()==true){
if (pair.getKey().toString().equalsIgnoreCase("Monday")) {
values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=MO");//UNTIL=1924885800000
}else if (pair.getKey().toString().equalsIgnoreCase("Tuesday")) {
values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=TU");
} else if (pair.getKey().toString().equalsIgnoreCase("Wednesday")) {
values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=WE");
} else if (pair.getKey().toString().equalsIgnoreCase("Thursday")) {
values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=TH");
} else if (pair.getKey().toString().equalsIgnoreCase("Friday")) {
values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=FR");
} else if (pair.getKey().toString().equalsIgnoreCase("Saturday")) {
values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=SA");
} else if (pair.getKey().toString().equalsIgnoreCase("Sunday")) {
values.put(CalendarContract.Reminders.RRULE, "FREQ=WEEKLY;COUNT=1;BYDAY=SU");
}
}
}
values.put(CalendarContract.Reminders.DTEND, EndtimeInMilliseconds);
)。
示例:
throws Exception
如果代码段生成void method()throws IOException{
}
,则会将其置于Exception
块内。然后提及处理try
块内Exception
的方法。
catch和handle的示例:
catch
此处尝试将try{
double a= parseDouble("12.4a");
}catch(NumberFormatException e){
System.out.println("cannot format");
}
转换为12.4a
并存储在double
中。由于a
包含字符12.4a
a
,因此会发生。你可以解决的。在上面的代码中我只打印一个文本。但是你得到NumberFormatException
:
printStackTrace
您可以在catch阻止后添加connect_by_isleaf
pseudocolumn。阅读finally
。
答案 2 :(得分:0)
是的,当然有一种方法可以做到这一点,它被称为异常处理。
首先阅读 window.undefined
类以及Exception
try
和catch
个关键字。
以下是一个起点:https://www.tutorialspoint.com/java/java_exceptions.htm