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?
The Throwable class is the superclass of all Java exceptions and errors.
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.
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.
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.
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 ... }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With