How to use try without catch in Java

How to use try without catch in Java:

We can use try without a catch or finally block in Java. But, you have to use a finally block.

The finally block always executes when the try block exits. finally block is executed even if an exception occurs. finally block is used for cleanup code. For example, if you open a file in the try block, you can close it inside finally.

If JVM exits, this block may not execute.

Example of try without catch block:

Let’s try it with an example:

class Main {
    public static void main(String[] args) {
        try {
            System.out.println("Inside try block..");
        } finally {
            System.out.println("Inside finally..");
        }
    }
}

This program will work. If you run this program, it will print the below output:

Inside try block..
Inside finally..

Exception inside try block:

Let’s try to throw an exception inside the try block.

class Main {
    public static void main(String[] args) {
        try {
            throw new NullPointerException();
        } finally {
            System.out.println("Inside finally..");
        }
    }
}

We are throwing a NullPointerException inside the try block. It will print:

Inside finally..
Exception in thread "main" java.lang.NullPointerException
	at Main.main(Main.java:4)

Process finished with exit code 1

Java exception try finally

Without catch block and with throws:

Let’s take a look at the below program:

class Main {

    private static void dummyMethod() throws NullPointerException {
        try {
            System.out.println("Inside dummyMethod try...");
            throw new NullPointerException();
        } finally {
            System.out.println("Inside finally..");
        }
    }

    public static void main(String[] args) {
        try {
            System.out.println("Inside main try...");
            dummyMethod();
        } finally {
            System.out.println("Inside main finally...");
        }
    }
}

In this example, I am calling a method dummyMethod that can throw a NullPointerException. Inside this method, we are throsing NullPointerException in the try block.

Both uses only try with only finally block and without catch block.

If you run this program, it will print the below output:

Inside main try...
Inside dummyMethod try...
Inside finally..
Inside main finally...
Exception in thread "main" java.lang.NullPointerException
	at Main.dummyMethod(Main.java:6)
	at Main.main(Main.java:15)

As you can see, it prints the statements in both finally blocks.

You might also like: