Runtime exceptions

DiVine features a set of exceptions that are thrown when the dependency injector detects illegal use of a dependency. This helps you to avoid many bugs in your code, as it tells you meaningful error messages.

Each exception of DiVine extends GenericServiceException. When accessing the container, it is guaranteed that all runtime exceptions will be an instance of this exception.

Here is a list of DiVine's exceptions.

CircularDependencyException

This exception is thrown when two or more dependencies reference each other.

For example:

@Service
class ServiceA {
    @Inject
    ServiceB serviceB;
}

@Service
class ServiceB {
    @Inject
    ServiceA serviceA;
}

In case of running Container.get(ServiceA.class), the dependency resolving stack grows like this:

ServiceA -> ServiceB -> ServiceA
                        ^^^^^^^^ duplicate member, circular dependency detected

UnknownDependencyException

This exception is thrown when a missing dependency is being accessed from the container.

For example:

void initDependencies() {
    Container.set("EXAMPLE_VALUE", "Hello, World");
    Container.set("OTHER_VALUE", 12345);
}

void useDependencies() {
    int myValue = Container.get("NOT_SPECIFIED_VALUE");
}

In this example, NOT_SPECIFIED_VALUE was not set, therefore accessing it from the container will throw an error.

InvalidServiceException

This exception is thrown when the container looks up a service with an invalid service descriptor.

For example:

class MyBadService {
    public void foo() {
    }
}

Using this service will throw an exception, because the service class is missing the @Service annotation.

void init() {
    Container.get(MyBadService.class);
}

ServiceInitializationException

This exception is thrown when the service throws an exception during its initialization process.

@Service
class MyService {
    public MyService() {
        throw new MyRuntimeException("Error whilst initializing service");
    }
}

When requesting an instance for this service, any runtime exception will be encapsulated with a ServiceInitializationException.

void foo() {
    try {
        Container.get(MyService.class);
    } catch (ServiceInitializationException e) {
        assert e.getCause() instanceof MyRuntimeException;
    }
}

ServiceRuntimeException

This exception is thrown when an exception occurrs whilst invoking a function for a service lifecycle event.

@Service
class MyService {
    @AfterInitialized
    public void init() {
        throw new ExampleRuntimeException();
    }
}

When an error is thrown in a method of lifecycle event handler, the error is encapsulated with a ServiceRuntimeException.

Last updated