When you call input.nextLine() as part of your exception catching is it better to place it into every catch block or just inside a finally block at the end of the try-catch. What is the advantage or disadvantage to either approach?
example:
catch (InputMismatchException e)
{
input.nextLine();
System.out.println("Cannot add to Database, please enter only integers");
}
catch (Exception e)
{
input.nextLine();
System.out.println("Impossible to add, please enter only letters from a-z");
}
Or
catch (InputMismatchException e)
{
System.out.println("Cannot add to Database, please enter only integers");
}
catch (Exception e)
{
System.out.println("Impossible to add, please enter only letters from a-z");
}
finally
{
input.nextLine();
}
What is the advantage or disadvantage to either approach?
Regards,
Pill.
If you want to read next line irrespective of exception conditions(exception raised or not raised whether it is handled or not handled) write input.nextLine()
in finally
block. If you want to read next line only when an exceptions raised and it is handled then write input.nextLine()
in respective catch
block.
catch
and finally
are different usage. finally
don't care about exception types, etc. So, use finally
when you need to execute code whether the method process ok or not.
catch
care about exception types. So, you handle when exceptoin occured. Because you don't want your application crash.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.