I've the following ternary expression:
((!f.exists()) ? (f.createNewFile() ? printFile() : throw new Exception("Error in creating file")) : printFile());
For one, or more, reason that I don't know idea IDE say to me that it isn't a statement. Why?
this is not valid, you need to return a value
printFile() : throw new Exception("Error in creating file")
try this one
if(f.exists() || f.createNewFile()) {
printFile();
}else{
throw new Exception("Error in creating file");
}
It looks like you are using it as a statement and not as an assignment
From what SO says it is not possible to do so
Also from another SO Articel, that says you can´t throw an exception in the ternary statement
I think you need to go back to an if-else clause like this:
if (!f.exists()) {
try {
f.createNewFile();
printFile();
} catch(Exception e ) {
System.out.println("Error in creating file");
}
} else {
printFile();
}
The "COND ? Statement : Statement" construct is an expression. It can not be used as a statement. Without assignment it can be used in situation like resolving condition argument in function call or string concatenation.
Func( (COND ? param1 : param2) );
"Hi"+(con?"Miss":"Mr.")+"";
The statements in the ternary operator need to be non-void . They need to return something.
Example:
System.out.println((count >10 ? true: false));
count >10 ? true: false
count >10 ? true: false
where compiler will complain that this is not a statement.
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.