Java with Groovy exception handling closures

We have a system that can be configured using groovy scripts, and I found a very strange effect on the type of exceptions that are thrown from these scripts.

We have a groovy script with the following:

process {
   throw new Exception("weeee")
}

The process is defined as Closing in the base class script:

public abstract class ScriptBaseClass extends Script {
   Closure process;

   public void process( Closure code ) {
      process = (Closure) code.clone();
   } 
}

In the Java class that actually runs the scripts, we have the following method (all installation code is omitted because it does not seem relevant):

public void process() {
   try {
      script.process.call();
   } catch (Exception e) {
      logger.debug("exception thrown from groovy script", e);
      throw e;
   }
}

Note that the process method here does not declare that it throws exceptions. However, he pretty clearly throws Exception e, which he caught. This code is valid, it compiles and works pretty happily. It throws an exception as I wanted.

- , ? , , .

+4
3

, Java- ( Java 7) . catch (Exception e) RuntimeException, () , call().

, : https://docs.oracle.com/javase/7/docs/technotes/guides/language/catch-multiple.html

, :

public void xxxxx() {
    try {
        System.out.println('Hi!'); //or anything else w/o declared exceptions
    } catch (Exception e) {
        throw e;
    }
}

Java , RuntimeException, .

:

public void xxxxx() {
    try {
        throw new IOException(); //or anything that have declared checked exception
    } catch (Exception e) {
        throw e;
    }
}

, IOException

+5

Groovy, JVM , . Java. catch RuntimeException ( Exception ), , , try-. Exception Throwable. , .

+1

- w0 . Java:

public class Demo {
    public void someMethod() {
        try {
            System.out.println("Hello");
        } catch (Exception e) {
            throw e;
        }
    }
}

, :

import java.sql.*;

public class Demo {
    public void someMethod() {
        try {
            Connection c = DriverManager.getConnection("", "", "");
        } catch (SQLException e) {
            throw e;
        }
    }
}
+1
source

All Articles