Java - Can final variables be initialized in static initialization block? - java

Based on my understanding of the Java language, static variables can be initialized in static initialization block.
However, when I try to implement this in practice (static variables that are final too), I get the error shown in the screenshot below:

Yes of course: static final variables can be initialized in a static block but.... you have implicit GOTOs in that example (try/catch is essentially a 'GOTO catch if something bad happens').
If an exception is thrown your final variables will not be initialized.
Note that the use of static constructs goes against Object-Oriented dogma. It may complicate your testing and make debugging more difficult.

You can do this but you need to exit the static block by throwing an exception - you can rethrow the exception that was caught or a new one. Generally this exception must be a RuntimeException. You really should not catch a generic Exception but more specific exception(s) that might be thrown from within your try block. Finally, if a static initializer throws an exception then it will render the class unusable during that specific run because the JVM will only attempt to initialize your class once. Subsequent attempts to use this class will result in another exception, such as NoClassDefFoundError.
So, to work, your initializer should read something like this:
static {
try {
...
} catch (Exception e) {
e.PrintStackTrace();
throw new InitializationFailedException("Could not init class.", e);
}
}
Assuming that InitializationFailedException is a custom RuntimeException, but you could use an existing one.

public class MyClass
{
private static final SomeClass myVar;
static
{
Object obj = null; // You could use SomeClass, but I like Object so you can reuse it
try
{
obj = new SomeClass(...);
}
catch(WhateverException err)
{
// Possibly nested try-catches here if the first exception is recoverable...
// Print an error, log the error, do something with the error
throw new ExceptionInInitializerError(err);
}
finally
{
myVar = (SomeClass) obj;
}
}
}
Assuming no where upstream is in a position to catch either an ExceptionInInitializationError or a general Exception then the program should not ever try to use myVar. If however those are caught and the program doesn't end, then you need to code to watch for and handle myVar being null (or be happy with NullPointerExceptions coming out all over).
I'm not sure there is a good way to handle this.

Can you put the declaration in the finally block?
try {
//load file
} catch(IOException e) {
// horay
} finally {
HOST=config.get......
}

Related

How to avoid exceptions when creating a URL?

In a JUnit test package, I create a java.net.URL object and use it in a variety of assert statements. However, the constructor for the URL Object throws a MalformedURLException that must be caught. Since that must be caught, the constructor must then be wrapped in a try/catch, and that means you have to put the variable in scope outside of the try/catch.
Example code:
URL ocURL = null;
try {ocURL = new URL("https://docs.oracle.com/javase/8/docs/api/java/net/URL.html");}
catch (MalformedURLException e) {}
assertEquals(variable, ocURL)
Admittedly, this is entirely aesthetic: I don't like all the extra code with no meaning littering my screen. Since I am passing the URL as a string, I know that it is going to be good, so that exception cannot be thrown (famous last words, though).
Is there a way to avoid declaring the URL object, then initializing it inside a try/catch? Is there a way to build a java.net.URL object without having to catch a (non-existent) exception?
create a static factory method instead and handle the try/catch only once:
private static URL createURL(String path) {
try {
return ....;
} catch(MalformedURLException e){
// handle somehow
throw new RuntimeException(e);
}
}

How to handle exception handling in singleton pattern?

I am trying to understand how to handle exception handling here. I have my below Singleton class which connects to cassandra, initialize all the metadata on the first call and then starts a periodic background thread which updates all our metadata every 15 minutes.
public class CassUtils {
private final ScheduledExecutorService scheduler = Executors.newSingleThreadScheduledExecutor();
private final CassSession cassSession;
private static class Holder {
private static final CassUtils INSTANCE = new CassUtils();
}
public static CassUtils getInstance() {
return Holder.INSTANCE;
}
private CassUtils() {
CassConfig config = Utils.getConfig();
try {
this.cassSession = new CassSession(config);
initializeMetadata(); // initializes metadata on the very first call
} catch (Exception ex) {
// log error
throw new IllegalStateException("cannot initialize metadata: " + ex.getMessage());
}
}
private void startScheduleTask() {
scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
try {
List<ProcessMetadata> processMetadata = getProcessMeta();
List<ClientMetadata> clientMetadata = getClientMeta();
List<ProcMetadata> procMetadata = getProcMeta();
if (!processMetadata.isEmpty() && !clientMetadata.isEmpty())
MetadataManager.setMetadata(processMetadata, clientMetadata, procMetadata);
} catch (Exception ex) {
// log error
}
}
}, 30, 15, TimeUnit.MINUTES);
}
private void initializeMetadata() {
List<ProcessMetadata> processMetadata = getProcessMeta(true);
List<ClientMetadata> clientMetadata = getClientMeta();
List<ProcMetadata> procMetadata = getProcMeta();
if (processMetadata.isEmpty() || clientMetadata.isEmpty() || procMetadata.isEmpty()) {
throw new IllegalStateException(); // is it ok to throw exception without any message here?
}
MetadataManager.setMetadata(processMetadata, clientMetadata, procMetadata);
startScheduleTask();
}
I need to notify the caller who is calling this singleton if there are any issues.
Now for whatever reason if CassSession throws exception because that is the class connects to cassandra and for some reason it is not able to connect to cassandra (mostly it will never happen), then I catch the exception in catch block in CassUtils class and throw IllegalStateException to the users with a message in it.
Also let's say if we are able to connect to cassandra through CassSession (which we will always) but in the initializeMetadata method, all our metadata are empty, then I don't want to proceed further so I am throwing IllegalStateException without any message in it. Is that ok? Because ultimately it will be caught by catch block of CassUtils class which is throwing exception to the calling users.
How to handle exception handling in singleton cases so that we can notify calling person whoever is calling this singleton. And IllegalStateException is the right exception to be thrown here? These above cases will happen during the first call at the initialization time. Is there any better way to do?
You are using static / class initialization to create the ClassUtils instance. As a general rule:
All checked exceptions that are thrown in class initialization must be caught. The compiler insists.
Any unchecked exceptions that propagate out of a classes static initialization will ultimately cause an Error to be thrown. Even in contexts where you are able to catch this error, you will be stuck with a class whose initialization has failed. The JVM won't ever retry the initialization, and the class ... and any other class that depends on it will be unusable.
So, if you were to deal with this, you would need to catch and (appropriately) handle the exception during static initialization.
Next problem is that if you want to report the failure to users of the CassUtils singleton, then getInstance() has to return an instance of CassUtils (or maybe a subclass) that is capable of:
remembering the exception, or whatever that reported the failure, and
rethrowing it to the caller of instance methods on the CassUtils API.
That is possible, but complicated.
And IMO it is undesirable. I think you would be best off NOT attempting to recover. Treat failure to initialize the Casandra session as a fatal error. If you can't do that, then the getInstance() method should be the method that throws / rethrows the exception that says "we are broken". At least, that avoids the need for potentially any caller of any CassUtils method to have to deal with the "we are broken" exception.
Did anyone ever mention to you that singletons are a bad idea? Consider using dependency injection instead.

Throwing exceptions from a helper function

Is the following static helper function an anti-pattern?
public class CustomException extends RuntimeException {
// ...
public static void rethrow(String s, Exception e) throws CustomException {
throw new CustomException(s + "\n" + "Exception: " + e.getMessage());
}
}
Couldn't see it on http://javapeanuts.blogspot.com/2012/02/exception-management-antipatterns.html or elsewhere.
One immediate problem is that static warnings get broken, eg I can't do the following anymore:
final Blah blah = null;
try {
blah = foo();
}
catch (Exception e) {
CustomException.rethrow("Couldn't blah", e);
}
bar = blah.bar(); // ERROR: Variable 'blah' might not have been initialized.
Hmmmm, I think I solved it. :-) I should create a constructor for CustomException that takes a String and Exception as args.
Yes, catching the RuntimeException and creating a new path inside your application isn't allowed, because it's completely wrong to catch the RuntimeException, as the main reason that it has been thrown has to mainly do with things like the resources of your system for example and such other things, not related with your code.
Instead, you should terminate the specified code's flow and inform the user respectively.
But, there are some cases that the depicted anti-pattern may sound better, so, you would better go through the following threads, in order to develop a better idea, according to your problem, at any given time:
Extending Exception/RunTimeException in java?
Need to create a new RunTimeException for EmptyStacks
Why would I extend java.lang.RuntimeException
When to choose checked and unchecked exceptions
The above are not more than words, which means that in the end, the final design (i.e. following the language specification/creating anti-patterns) is up to you, but what you should always keep in mind (and decide/act accordingly, per case) is that one layer's runtime exception is another layer's checked (and acted upon) exception.

Is it possible to ignore an exception?

In Java, is it possible to make a method that has a throws statement to be not checked.
For example:
public class TestClass {
public static void throwAnException() throws Exception {
throw new Exception();
}
public static void makeNullPointer() {
Object o = null;
o.equals(0);//NullPointerException
}
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
throwAnException(); //I'm forced to handle the exception, but I don't want to
}
}
You can try and do nothing about it:
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
try {
throwAnException(); //I'm forced to handle the exception, but I don't want to
} catch (Exception e) { /* do nothing */ }
}
Bear in mind, in real life this is extemely ill-advised. That can hide an error and keep you searching for dogs a whole week while the problem was really a cat(ch). (Come on, put at least a System.err.println() there - Logging is the best practice here, as suggested by #BaileyS.)
Unchecked exceptions in Java extend the RuntimeException class. Throwing them will not demand a catch from their clients:
// notice there's no "throws RuntimeException" at the signature of this method
public static void someMethodThatThrowsRuntimeException() /* no need for throws here */ {
throw new RuntimeException();
}
Classes that extend RuntimeException won't require a throws declaration as well.
And a word from Oracle about it:
Here's the bottom line guideline: If a client can reasonably be expected to recover from an exception, make it a checked exception. If a client cannot do anything to recover from the exception, make it an unchecked exception.
There are 3 things you can do :
Throw a RuntimeException (or something extending a RuntimeException, like NullPointerException, IllegalArgumentException,...), you don't have to catch these as they are unchecked exceptions.
Catch the exception and do nothing (not recommended) :
public static void exceptionTest() {
makeNullPointer(); //The compiler allows me not to check this
try {
throwAnException(); //I'm forced to handle the exception, but I don't want to
} catch (Exception e) {
// Do nothing
}
}
Change exceptionTest () declaration to say that it throws an Exception, and let the method calling it catch the Exception and do what is appropriate :
public static void exceptionTest() throws Exception {
makeNullPointer(); //The compiler allows me not to check this
throwAnException(); //I'm no more forced to handle the exception
}
In Java there is two kinds of Exceptions, Checked Exceptions and Unchecked Exceptions.
Exception is a checked exception, must caught or thrown.
NullPointerException is a RuntimeException, (the compiler doesn’t forces them to be declared in the throws claus) you can ignore it, ,but it still may occur in the Runtime, and your application will crash.
From Exception documentation:
The class Exception and any subclasses that are not also subclasses of
RuntimeException are checked exceptions. Checked exceptions need to be
declared in a method or constructor's throws clause if they can be
thrown by the execution of the method or constructor and propagate
outside the method or constructor boundary.
From the RuntimeException documentation:
RuntimeException is the superclass of those exceptions that can be
thrown during the normal operation of the Java Virtual Machine.
RuntimeException and its subclasses are unchecked exceptions.
Unchecked exceptions do not need to be declared in a method or
constructor's throws clause if they can be thrown by the execution of
the method or constructor and propagate outside the method or
constructor boundary.
No, it raises a compiler error. Being a checked exception, you must either catch it or propagate it by declaring your method as potentially throwing it.
Check this and this.
Throw a RuntimeException or an exception which is derived from RuntimeException. Then the compiler will not force you to catch it.
The other answers are right, in that they correctly tell you what you should do, but it is actually possible to throw a undeclared checked exception. There are a few ways this can be done; the simplest is:
public void methodThatSecretlyThrowsAnException() {
Thread.currentThread().stop(new Exception());
}
or if your goal is to wrap an existing method that does declare its exception
public void methodThatSecretlyThrowsAnException() {
try {
methodThatAdmitsItThrowsAnException();
} catch(final Exception e) {
Thread.currentThread().stop(e);
}
}
(Needless to say, you should never do this.)
Just catch an exception and dont do any thing with it, leave it as it is and catch the generic exception in case you are not aware of the specific exception
try{
//Your logic goes here
}
catch(Exception e)//Exception is generic
{
//do nothing
}
AS I know, it's impossible in the case. Only unchecked exception, compiler can skip to check. such as RuntimeException.
You can use a loophole in the Java Compiler. Add the following code:
public RuntimeException hideThrow(Throwable e) {
if (e == null)
throw new NullPointerException("e");
this.<RuntimeException>hideThrow0(e);
return null;
}
#SuppressWarnings("unchecked")
private <GenericThrowable extends Throwable> void hideThrow0(Throwable e) throws GenericThrowable {
throw (GenericThrowable) e;
}
You can catch the exception, then invoke hideThrow with the exception to throw it without the compiler noticing. This works because of type erasure. At compile time, GenericThrowable represents RuntimeException because that is what we are passing. At run time, GenericThrowable represents Throwable because that is the basic type in the type parameter specification.
It is not advisable to avoid an exception with an empty catch block even though you are completely sure that is not going to fail under any circumstance. Sometimes, we are not aware of the human factor.
If you are sure that an exception is very unlikely to happen (if not impossible) you should create your own Exception and and wrap the unexpected exception in it.
For example:
private class UnlikelyException extends RuntimeException {
public UnlikelyException (Exception e){
super (e);
}
}
Then wrap your code with a try-catch block and throw your exception, which you don't have to catch
try {
// Your code
} catch (Exception e) {
throw new UnlikelyException(e);
}

Wrap exceptions by runtime exceptions with an annotation

Is there a way to annotate a method so all exceptions thrown are converted to runtime exception automagically?
#MagicAnnotation
// no throws clause!
void foo()
{
throw new Exception("bar")'
}
Project Lombok's #SneakyThrows is probably what you are looking for. Is not really wrapping your exception (because it can be a problem in a lot of cases), it just doesn't throw an error during compilation.
#SneakyThrows
void foo() {
throw new Exception("bar")'
}
You can do this with AspectJ. You declare a joinpoint (in this case invocation of the method foo) and 'soften' the exception.
Edit To elaborate a bit on this:
Say you have the following class Bar:
public class Bar {
public void foo() throws Exception {
}
}
...and you have a test like this:
import junit.framework.TestCase;
public class BarTest extends TestCase {
public void testTestFoo() {
new Bar().foo();
}
}
Then obviously the test is not going to compile. It will give an error:
Unhandled exception type Exception BarTest.java(line 6)
Now to overcome this with AspectJ, you write a very simple aspect:
public aspect SoftenExceptionsInTestCode {
pointcut inTestCode() : execution(void *Test.test*());
declare soft : Exception : inTestCode();
}
The aspect basically says that any code from within a Test (i.e.: a method that starts with "test" in a class that ends in "Test" and returns 'void') that throws an exception should be accepted by the AspectJ compiler. If an exception occurs, it will be wrapped and thrown as a RuntimeException by the AspectJ compiler.
Indeed, if you run this test as part of an AspectJ project from within Eclipse (with AJDT installed) then the test will succeed, whereas without the aspect it won't even compile.
No way to do that, at least for now I use workaround like this (simplified):
#SuppressWarnings({"rawtypes", "unchecked"})
public class Unchecked {
public static interface UncheckedDefinitions{
InputStream openStream();
String readLine();
...
}
private static Class proxyClass = Proxy.getProxyClass(Unchecked.class.getClassLoader(), UncheckedDefinitions.class);
public static UncheckedDefinitions unchecked(final Object target){
try{
return (UncheckedDefinitions) proxyClass.getConstructor(InvocationHandler.class).newInstance(new InvocationHandler(){
#Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if (target instanceof Class){
return MethodUtils.invokeExactStaticMethod((Class) target, method.getName(), args);
}
return MethodUtils.invokeExactMethod(target, method.getName(), args);
}
});
}
catch(Exception e){
throw new RuntimeException(e);
}
}
}
And the usage looks like:
import static ....Unchecked.*;
...
Writer w = ...;
unchecked(w).write(str, off, len);
The trick is that interface is "never finished" and everytime I need unchecked method somewhere, I'll wrap that object into unchecked and let IDE generate method signature in interface.
Implementation is then generic (reflective and "slow" but usually fast enough)
There are some code post-processors and bytecode-weavers but this was not possible (not even aop or other jvm based language) for my current project, so this was "invented".
I think it is possible with bytecode re-engineering, customized compiler or perhaps aspect oriented programming1. In the contrary to Java, C# has only unchecked exceptions2.
May I ask why you want to suppress the checked exceptions?
1 according to Maarten Winkels this is possible.
2 and they are thinking about introducing checked ones, according to some Channel 9 videos.
Edit: For the question: It is possible in the sense that you can annotate your methods to flag them to be a candidate for checked exception suppression. Then you use some compile time or runtime trick to apply the actual suppression / wrapping.
However, as I don't see the environment around your case, wrapping an exception in these ways might confuse the clients of that method - they might not be prepared to deal with a RuntimeException. For example: the method throws an IOException and your clients catches it as FileNotFoundException to display an error dialog. However if you wrap your exception into a RuntimeException, the error dialog gets never shown and probably it kills the caller thread too. (IMHO).
The Checked exceptions are responsability of the method implementation.
Take very very carefully this fact. if you can do not use workaround artifacts like that.
You can do this in any case via use of the fact that Class.newInstance does not wrap an Exception thrown by the no-arg constructor in an InvocationTargetException; rather it throws it silently:
class ExUtil {
public static void throwSilent(Exception e) { //NOTICE NO THROWS CLAUSE
tl.set(e);
SilentThrower.class.newInstance(); //throws silently
}
private static ThreadLocal<Exception> tl = new ThreadLocal<Exception>();
private static class SilentThrower {
SilentThrower() throws Exception {
Exception e = tl.get();
tl.remove();
throw e;
}
}
}
Then you can use this utility anywhere:
ExUtil.throwSilent(new Exception());
//or
try {
ioMethod();
} catch (IOException e) { ExUtil.throwSilent(e); }
By the way, this is a really bad idea :-)
I use the completion / template system of Eclipse to wrap any block of code easily.
Here is my template :
try { // Wrapp exceptions
${line_selection}${cursor}
} catch (RuntimeException e) { // Forward runtime exception
throw e;
} catch (Exception e) { // Wrap into runtime exception
throw new RuntimeException(
"Exception wrapped in #${enclosing_method}",
e);
}

Categories