Concept

How can Java handle different exception types with multiple catch blocks?

ComputerScienceOne / Catching Exceptions

"The code above could have resulted in other exceptions. For example if the Scanner had failed to read the next token from the standard input, it would have thrown a NoSuchElementException. We can add as many catch blocks as we want to handle each exception differently.\n\nScanner s = new Scanner(System.in);\n\nint n = 0;\n\ntry {\n\nString input = s.next();\n\nn = Integer.parseInt(input);\n\n} catch (NumberFormatException nfe) {\n\nSystem.err.println(\"You entered invalid data!\");\n\nSystem.exit(1);\n\n} catch (NoSuchElementException nsee) {\n\nSystem.err.println(\"Input reading failed, using default...\");\n\nn = 20; //a default value\n\n} catch(Exception e) {\n\nSystem.err.println(\"A general exception occurred\");\n\ne.printStackTrace();\n\nSystem.exit(1);\n\n}\n\nEach catch block catches a different type of exception. Thus, the name of the variable that holds each exception must be different in the chain of catch blocks; nfe, nsee, e."

Related Ideas

How can Java handle different exception types with multiple catch blocks? | ComputerScienceOne | Bifalgorithm | Bifalgorithm