java - Error handling with if statement -
this validate gui input , create sure user can not come in values out of range
i'm trying handle exception if statement i'm still printing reddish error message. want "value out of range" message printed. don't want reddish exceptions error in console. please help or advise. other way handle can fine me.
if (totaltimetotakeoff <= 0 || totaltimetoland <= 0 || arrivalrate < 0 || arrivalrate > 1 || departurerate < 0 || departurerate > 1 || remaingfuel <= 0 || numofrunways <= 0 || simulation_time < 0) { throw new illegalargumentexception("values out of range"); }
well doing here creating new illegalargumentexception object, , method throws exception. when throw exception, part of code calls method has handle exception or 'red lines' (the stack trace, basically) printed. so, simple example, have method divide()
public double divide(double a, double b){ if(b==0){ throw new illegalargumentexception("divisor cannot 0"); } homecoming a/b; } now, when other part of code calls method, can take handle illegalargumentexception thrown method.
try{ double c = divide(a,b); }catch(illegalargumentexception e){ //put whatever code want here } if don't grab exception, code breaks , stack trace (the reddish text) printed out. in other words, code functioning intended; section of code throws illegalargumentexception under circumstance, , code calls method not grab exception , handle (for illustration printing out message exception).
also, minor note- error in java different exception. error signifies process programme cannot recover, , error cannot caught. exceptions (all classes subclass exception class) can caught. exception can either checked or unchecked - checked exceptions must caught via grab statement, whereas unchecked exceptions don't. illustration of checked exception ioexception, whereas illustration of unchecked exception illegalargumentexception have displayed here.
one more thing- exceptions meant signify abnormality in code. if illegalargumentexception thrown say, class constructor or method can used many general purposes, makes sense throw it. however, if method exists solely purpose of checking whether input valid, have homecoming boolean value (true or false) rather throwing exception.
one other reason because exception handling tends rather slow in comparing returning true or false.
java
No comments:
Post a Comment