exception - Java NoSuchElementException -


so have pretty big java application wrote year ago , i'm trying understand again. i'm looking @ method in code there obvious risk of getting nosuchelementexception: i'm calling .next() on scanner variable has been constructed arbitrary string. thing method declared throw custom made subclasses of exception. risky command isn't written in catch-block either. code compiles , works fine , when use gui in such fashion should throw nosuchelementexception nothing happens :o

as test wrote catch-block code, compiled it, ran gui , made throw nosuchelementexception again , application caught exception , acted accordingly. how can compile code without specifying exception may thrown? if it's use @ all, here code without catch-block:

public static expression interpret(final scanner scanner)   throws     invalidposition,     nosuchspreadsheet,     illegalstartofexpression,     invalidexpression,     falsesyntax,     invalidrange {  string keyword = null;  try {   keyword = scanner.next(); } catch (nosuchelementexception e) {   throw new illegalstartofexpression(); }  switch(keyword) {   case "get":     position pos = positioninterpreter.interpret(scanner.next());     expression expression = application.instance.get(pos);     if (expression instanceof text) {         system.out.println("failure");     } else { system.out.println("success"); }     return new text(expression.tostring());   case "int":     return new int(       scanner.nextint()); 

as can see, method assumes there more 1 word in scanner after checking if there @ least one. how getting away compiling this?

it cause nosuchelementexception unchecked exception, means "is-a" runtimeexception not force catch.

the unchecked exceptions classes class runtimeexception , subclasses, , class error , subclasses. other exception classes checked exception classes. java api defines number of exception classes, both checked , unchecked. additional exception classes, both checked , unchecked, may declared programmers. see ref description of exception class hierarchy , of exception classes defined java api , java virtual machine.

runtime exceptions serve same purpose checked exceptions; communicate exceptional conditions (unexpected failures, etc) user.

checked exception forces caller of method handle exception, if not know how handle it. times, developers end catching checked exception, re-throw (or exception). hence runtime exceptions

here exception hierarchy

enter image description here


Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -