ignoreIfMissing method example

In this post under DotEnv I will show with example what is the purpose of “ignoreIfMissing” method with an example.

In my previous posts I showed with example how to load environment files whether it is “.env” file or custom env file like “custom-file.env”.

The default behavior of DotEnv framework is that if the environment file is not found it will thrown an exception.

We can change this default behavior.

We can configure DotEnv to not throw an exception if it hasn’t found the specified environment file.

That is where “ignoreIfMissing” method comes into picture.

Calling this method configures the “DotEnv” instance to not throw exception if the environment file doesn’t exist.

Below is the main class that shows how to configure “DotEnv” instance to not throw an exception if the environment file doesn’t exist.

Main Class

1  package defaultPackage;
2
3 import io.github.cdimascio.dotenv.Dotenv;
4 import io.github.cdimascio.dotenv.DotenvException;
5
6 public class Example5 {
7 public static void main(String[] args) {
8 try {
9 Dotenv dotenv = Dotenv.configure().filename("custom-file1.env").load();
10 System.out.println("First Attempt: Exception not thrown");
11 }catch (DotenvException dotenvException) {
12 System.out.println("First Attempt: Exception thrown");
13 }
14
15 try {
16 Dotenv dotenv = Dotenv.configure().filename("custom-file1.env").ignoreIfMissing().load();
17 System.out.println("Second Attempt: Exception not thrown");
18 } catch(DotenvException dotenvException) {
19 System.out.println("Second Attempt: Exception thrown");
20 }
21 }
22 }

In the above main class, there are two try catch blocks.

In first try catch block, I created a “DotEnv” instance which will try to load environment file “custom-file1.env”.

The file “custom-file1.env” doesn’t exist, so it will throw an exception.

In second try catch block, I again created another “DotEnv” instance but this time while creating it I have called “ignoreIfMissing” method.

As a result the “DotEnv” instance which gets created doesn’t throw an exception if the file “custom-file1.env” doesn’t exist.

So in this case it will not throw an exception.

In this way we use “ignoreIfMissing” method.

Below is the output for your reference

Output

First Attempt: Exception thrown
Second Attempt: Exception not thrown

Leave a comment