Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unhandled exceptions in field initializations

Does Java have any syntax for managing exceptions that might be thrown when declaring and initializing a class's member variable?

public class MyClass {   // Doesn't compile because constructor can throw IOException   private static MyFileWriter x = new MyFileWriter("foo.txt");    ... } 

Or do such initializations always have to be moved into a method where we can declare throws IOException or wrap the initialization in a try-catch block?

like image 714
kpozin Avatar asked Jun 22 '09 18:06

kpozin


People also ask

What is the super class for exception in Java?

The Throwable class is the superclass of all Java exceptions and errors.

What are the compile time exceptions in Java?

Checked exceptions are also known as compile-time exceptions as these exceptions are checked by the compiler during the compilation process to confirm whether the exception is handled by the programmer or not. If not, then the system displays a compilation error.

What is unhandled exception type?

An exception is a known type of error. An unhandled exception occurs when the application code does not properly handle exceptions. For example, When you try to open a file on disk, it is a common problem for the file to not exist.

Which of the following class is the checked exception in Java?

The checked exception classes are all exception classes other than the unchecked exception classes. That is, the checked exception classes are all subclasses of Throwable other than RuntimeException and its subclasses and Error and its subclasses.


1 Answers

Use a static initialization block

public class MyClass {   private static MyFileWriter x;    static {     try {       x = new MyFileWriter("foo.txt");      } catch (Exception e) {       logging_and _stuff_you_might_want_to_terminate_the_app_here_blah();     } // end try-catch   } // end static init block   ... } 
like image 138
MattC Avatar answered Oct 08 '22 21:10

MattC