Jumping from Batch.Execute to Batch.Finish is not possible. If there is any unhandled error i.e. any exception was thrown in code within execute method data changes made within that execute block are rolled back and that particular batch is marked for failure(just that execute instance not all)
You can use system.abortjob within execute method to immediately abort the job but that will not call finish method. But you can encapsulate processing that you are doing in finish method by creating a new private method and then call if from execute and finish both. From execute this new method will be called conditionally before you abort the job.
Here is code sample to clarify this.
public class CSVBatch implements Database.Batchable<String>
{
public Iterable<String> start(Database.BatchableContext BC)
{
List<String> csvLines = new List<String>();
for(integer i = 1; i < 500; i++)
csvLines.add(String.valueOf(i));
return csvLines;
}
public void execute(Database.BatchableContext BC, List<String> scope)
{
for(String s : scope)
{
if(s == '120')
{
//case 1 - We don't want to process further in batch
//Do finish processing here
mycustomfinish();
//After that abort the Job
system.abortJob(BC.getJobId());
}
else if(s == '420')
{
//Case 2 - We just want to skip current batch
throw new AppException('Skipped current batch');
}
else
{
//do some processing
}
}
}
public void finish(Database.BatchableContext BC)
{
mycustomfinish();
}
private void mycustomfinish()
{
system.debug('finish called');
}
public class AppException extends Exception{}
}