Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is best way to leave a groovy script prematurely (except system.exit(0))

Tags:

groovy

what is best way to leave a groovy script prematurely ?

A groovy script reads a row from a given info file then makes some verification work, in case of verification fails (inconsistent data) script needs to leave the flow prematurely . Then system will call the script again to read next row of the same info file

Code example :

 read a row  try{    //make some verification here  }catch(Exception e){     logger("exception on something occurred "+e,e)     //here need to leave a groovy script prematurely  } 
like image 879
Toren Avatar asked Sep 12 '12 08:09

Toren


People also ask

How do I return a value in groovy?

The last line of a method in Groovy is automatically considered as the return statement. For this reason, an explicit return statement can be left out. To return a value that is not on the last line, the return statement has to be declared explicitly.


2 Answers

I'm pretty sure you can just return from a script.

like image 109
Todd W Crone Avatar answered Sep 23 '22 15:09

Todd W Crone


Just use System.exit(0).

try {     // code } catch(Exception e) {     logger("exception on something occurred "+e,e)     System.exit(0) } 

You could use the exit status code to indicate what line you had problems with.

A zero value would indicate that everything was OK, and a positive value would be the line number. You could then let your groovy script take the start line as an input parameter.


This is a naive implementation with just a silly exception if a line is empty.

file = new File(args[0]) startLine = args[1].toInteger()  file.withReader { reader ->     reader.eachLine { line, count ->         try {             if (count >= startLine) {                 if (line.length() == 0) throw new Exception("error")                 println count + ': ' + line             }         } catch (Exception ignore) {             System.exit(count)         }     } } 
like image 28
maba Avatar answered Sep 22 '22 15:09

maba