views:

119

answers:

4

I have classes DirReader and Search. The search uses DirReader. I want the search to know when DirReader throws exception. So how can I have class throwing exception?

Currently, I use initCorrect -dummy var. Exception-style method may be more appropriate.

Simplified Example Error

$ javac ExceptionStatic.java 
ExceptionStatic.java:4: '{' expected
public class ExceptionStatic throws Exception{
                            ^
1 error

Code

import java.util.*;
import java.io.*;

// THIS PART NEEDS TO BE FIXED:
public class ExceptionStatic throws Exception{

    private static boolean initCorrect = false;

    public static String hello;
    static{
        try{
            hello = "hallo";

            //some other conditionals in real code
            if( true) throw new Exception();

            initCorrect=true;
        }catch(Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args){
        if(initCorrect)
            System.out.println(hello);
    }
}
+1  A: 

Classes cannot throw exceptions. Only methods may throw exceptions. Avoid using the base Exception class. Throw a specific exception like IllegalStateException or extend Exception and make your own.

Jonathon
+2  A: 

You have a static code block that throws an exception? If you really need to do this throw a RuntimeException - otherwise move your logic into a method associated with a DirReader or Search class and have those methods throw the appropriate Exception.

Here's an example you can start with:

public class test { 


    static {
        try {
            method1();
        } catch (InterruptedException e) {
            throw new RuntimeException();
        }
    }

    protected static void method1() throws InterruptedException {        
        Thread.sleep(1000);        
    }


}
Amir Afghani
RuntimeException cannot be thrown from a static initialization block. You will get a compile error "Initializer does not complete normally".
Jonathon
Note that throwing a RuntimeException will make the classloader throw an exception, and class loading is relatively unpredictable (except that it happens before you use the class).
Kathy Van Stone
@jonathon I just tried a class that threw a NullPointerException in a static initializer. It compiled okay, but threw java.lang.ExceptionInInitializerError when I tried to access it. It is *not* a good idea to ever throw an exception in a static initializer
Kathy Van Stone
@jonathon That's not true. Granted you can't have a static init block that is guaranteed to throw a RuntimeException, but its perfectly acceptable to transform checked exceptions into unchecked exceptions in a catch block in a static initializer.
Jherico
Jonathan, try the example I posted.
Amir Afghani
@Jherico - ah, my mistake. I just tried a static initializer with the a `throw new RuntimeException()`, which the compiler errors on. Regardless, it's a really bad idea.
Jonathon
I agree its a horrible idea, it works though.
Amir Afghani
Whether its a bad idea is debatable. Basically there are times you want to initialize static members with code that can throw checked exceptions. In such cases you really have no choice but to convert them to unchecked exceptions.
Jherico
+2  A: 
erickson
What you can then do is have each method in the DirReader class throw an exception if it failed to initialize correctly.
Kathy Van Stone
+2  A: 

The throws keyword cannot be applied at class level, only at the method level.

fastcodejava