ballerina-platform / ballerina-spec

Ballerina Language and Platform Specifications
Other
168 stars 53 forks source link

Improvement for `on fail` clause by adding a `final` statement #1308

Closed SasinduDilshara closed 2 months ago

SasinduDilshara commented 3 months ago

Ballerina currently supports the do and on fail constructs, which are equivalent to try and catch in Java. However, there is no direct equivalent of the finally block in Java. This absence makes it challenging to ensure that certain cleanup actions are performed after the execution of a do block, regardless of whether an error occurs.

So isn't it better if we can introduce a finally keyword, like following

public function main() {
    do {
        // Code that may throw an error
    } on fail (error e) {
        // Error handling code
    } finally {
        // Cleanup code that runs regardless of success or failure
    }
}
jclark commented 2 months ago

I considered this in the past and don't think it's a good idea. There is a strong distinction between errors and panics in Ballerina, which this isn't consistent with.

sanjiva commented 2 months ago

In any case, if you just put the code after the statement it runs regardless of success or failure (as long as the block doesn't return):

public function main() {
    do {
        // Code that may result in an error
    } on fail (error e) {
        // Error handling code
    } 
    **// This code that runs regardless of success or failure**
}
jclark commented 2 months ago

But it doesn't get run on a panic, which is a problem if you try to use it for cleanup.

sanjiva commented 2 months ago

True but on fail is about errors not panics (as you said in the earlier comment) and the developer can convert the panic to an error if they want to handle panics too although not conveniently as panics can happen nearly anywhere.