Java try without catch and finally

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.

Источник

The try-with-resources Statement

The try -with-resources statement is a try statement that declares one or more resources. A resource is an object that must be closed after the program is finished with it. The try -with-resources statement ensures that each resource is closed at the end of the statement. Any object that implements java.lang.AutoCloseable , which includes all objects which implement java.io.Closeable , can be used as a resource.

The following example reads the first line from a file. It uses an instance of FileReader and BufferedReader to read data from the file. FileReader and BufferedReader are resources that must be closed after the program is finished with it:

static String readFirstLineFromFile(String path) throws IOException < try (FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr)) < return br.readLine(); >>

In this example, the resources declared in the try -with-resources statement are a FileReader and a BufferedReader . The declaration statements of these resources appear within parentheses immediately after the try keyword. The classes FileReader and BufferedReader , in Java SE 7 and later, implement the interface java.lang.AutoCloseable . Because the FileReader and BufferedReader instances are declared in a try -with-resource statement, they will be closed regardless of whether the try statement completes normally or abruptly (as a result of the method BufferedReader.readLine throwing an IOException ).

Prior to Java SE 7, you can use a finally block to ensure that a resource is closed regardless of whether the try statement completes normally or abruptly. The following example uses a finally block instead of a try -with-resources statement:

static String readFirstLineFromFileWithFinallyBlock(String path) throws IOException < FileReader fr = new FileReader(path); BufferedReader br = new BufferedReader(fr); try < return br.readLine(); >finally < br.close(); fr.close(); >>

However, this example might have a resource leak. A program has to do more than rely on the garbage collector (GC) to reclaim a resource’s memory when it’s finished with it. The program must also release the resoure back to the operating system, typically by calling the resource’s close method. However, if a program fails to do this before the GC reclaims the resource, then the information needed to release the resource is lost. The resource, which is still considered by the operaing system to be in use, has leaked.

In this example, if the readLine method throws an exception, and the statement br.close() in the finally block throws an exception, then the FileReader has leaked. Therefore, use a try -with-resources statement instead of a finally block to close your program’s resources.

If the methods readLine and close both throw exceptions, then the method readFirstLineFromFileWithFinallyBlock throws the exception thrown from the finally block; the exception thrown from the try block is suppressed. In contrast, in the example readFirstLineFromFile , if exceptions are thrown from both the try block and the try -with-resources statement, then the method readFirstLineFromFile throws the exception thrown from the try block; the exception thrown from the try -with-resources block is suppressed. In Java SE 7 and later, you can retrieve suppressed exceptions; see the section Suppressed Exceptions for more information.

The following example retrieves the names of the files packaged in the zip file zipFileName and creates a text file that contains the names of these files:

public static void writeToFileZipFileContents(String zipFileName, String outputFileName) throws java.io.IOException < java.nio.charset.Charset charset = java.nio.charset.StandardCharsets.US_ASCII; java.nio.file.Path outputFilePath = java.nio.file.Paths.get(outputFileName); // Open zip file and create output file with // try-with-resources statement try ( java.util.zip.ZipFile zf = new java.util.zip.ZipFile(zipFileName); java.io.BufferedWriter writer = java.nio.file.Files.newBufferedWriter(outputFilePath, charset) ) < // Enumerate each entry for (java.util.Enumeration entries = zf.entries(); entries.hasMoreElements();) < // Get the entry name and write it to the output file String newLine = System.getProperty("line.separator"); String zipEntryName = ((java.util.zip.ZipEntry)entries.nextElement()).getName() + newLine; writer.write(zipEntryName, 0, zipEntryName.length()); >> >

In this example, the try -with-resources statement contains two declarations that are separated by a semicolon: ZipFile and BufferedWriter . When the block of code that directly follows it terminates, either normally or because of an exception, the close methods of the BufferedWriter and ZipFile objects are automatically called in this order. Note that the close methods of resources are called in the opposite order of their creation.

The following example uses a try -with-resources statement to automatically close a java.sql.Statement object:

public static void viewTable(Connection con) throws SQLException < String query = "select COF_NAME, SUP_ID, PRICE, SALES, TOTAL from COFFEES"; try (Statement stmt = con.createStatement()) < ResultSet rs = stmt.executeQuery(query); while (rs.next()) < String coffeeName = rs.getString("COF_NAME"); int supplierID = rs.getInt("SUP_ID"); float price = rs.getFloat("PRICE"); int sales = rs.getInt("SALES"); int total = rs.getInt("TOTAL"); System.out.println(coffeeName + ", " + supplierID + ", " + price + ", " + sales + ", " + total); >> catch (SQLException e) < JDBCTutorialUtilities.printSQLException(e); >>

The resource java.sql.Statement used in this example is part of the JDBC 4.1 and later API.

Note: A try -with-resources statement can have catch and finally blocks just like an ordinary try statement. In a try -with-resources statement, any catch or finally block is run after the resources declared have been closed.

Suppressed Exceptions

An exception can be thrown from the block of code associated with the try -with-resources statement. In the example writeToFileZipFileContents , an exception can be thrown from the try block, and up to two exceptions can be thrown from the try -with-resources statement when it tries to close the ZipFile and BufferedWriter objects. If an exception is thrown from the try block and one or more exceptions are thrown from the try -with-resources statement, then those exceptions thrown from the try -with-resources statement are suppressed, and the exception thrown by the block is the one that is thrown by the writeToFileZipFileContents method. You can retrieve these suppressed exceptions by calling the Throwable.getSuppressed method from the exception thrown by the try block.

Classes That Implement the AutoCloseable or Closeable Interface

See the Javadoc of the AutoCloseable and Closeable interfaces for a list of classes that implement either of these interfaces. The Closeable interface extends the AutoCloseable interface. The close method of the Closeable interface throws exceptions of type IOException while the close method of the AutoCloseable interface throws exceptions of type Exception . Consequently, subclasses of the AutoCloseable interface can override this behavior of the close method to throw specialized exceptions, such as IOException , or no exception at all.

Источник

Can we have try without catch block in java

You can use try with finally. As you know finally block always executes even if you have exception or return statement in try block except in case of System.exit().

Lets understand with the help of example.

When you execute above program, you will get following output:

What happens when you have return statement in try block:

If you have return statement in try block, still finally block executes.

When you execute above program, you will get following output:

What happens if you have return statement in finally block too

It overrides whatever is returned by try block. Lets understand with the help of example:

When you execute above program, you will get following output:

What if exception is thrown in try block

If exception is thrown in try block, still finally block executes.

When you execute above program, you will get following output:

As you can see that even if code threw NullPointerException, still finally block got executed.
You can go through top 50 core java interview questions for more such questions.

Was this post helpful?

Share this

Author

Java try with resources

Table of ContentsOlder approach to close the resourcesJava 7 try with resourcesSyntaxExampleJava 9 Try with resources ImprovementsFinally block with try with resourcesCreate Custom AutoCloseable Code In this post, we will see about Java try with resources Statement. Java try with resources is a feature of Java which was added into Java 7. It helps to […]

Exception Handling Interview Questions

Java Exception Handling Interview Questions And Answers

Table of ContentsQuestion 1: What is Exception ?Question 2: How can you handle exception in java?Question 4: Difference between checked exception, unchecked exceptionand and errorsQuestion 5: Can we have try without catch block in java ?Question 6: What is RunTime exception in java?Question 7: What is checked exception or compile time exception?Question 8: Can you put […]

Difference between throw and throws in java

Table of Contentsthrow:throws: In this tutorial, we are going to see difference between throw and throws in java. throw: throw keyword is used to throw any custom exception or predefine exception. For example: Let’s say you want to throw invalidAgeException when employee age is less than 18. Create a Employee class as below. [crayon-64bf4f981c529340112679/] Create […]

Exception handling in java

Table of ContentsExceptionsWhat is Exception ?Exceptions hierarchy ThrowableExceptionRuntimeExceptionErrorChecked ExceptionsOCAJP checked exceptionsUnchecked ExceptionsOCAJP unchecked ExceptionsArrayIndexOutOfBoundsException ClassCastExceptionIllegalArgumentException NullPointerExceptionNumberFormatExceptionErrors ExceptionInInitializerErrorStackOverflowErrorNoClassDefFoundErrorDifference between checked exception, unchecked exception and errorsConclusionReferences Exceptions I have started writing about the and how to prepare for the various topics related to OCAJP exams in my blog. In my previous post, I have published few sample mock questions for StringBuilder […]

How to create custom exception in java

In this post, we will see how to create custom exception in java. It is very simple to create custom exception in java. You just need to extends Exception class to create custom exception. Lets understand this with example. You have list of counties and if You have “USA” in list of country, then you […]

Difference between checked and unchecked exception in java

Table of ContentsWhat is Exception?What is checked exception?What is unchecked exception? In this post, we will see difference between checked and unchecked exception in java. It is important question regarding exceptional handling. What is Exception? Exception is unwanted situation or condition while execution of the program. If you do not handle exception correctly, it may […]

Источник

Читайте также:  Пути
Оцените статью