17

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);
    }
}
hhh
  • 50,788
  • 62
  • 179
  • 282

6 Answers6

44

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

fastcodejava
  • 39,895
  • 28
  • 133
  • 186
6

It is a compile-time error for a class initializer ("static block") to terminate with a checked exception.

If a class initializer throws an unchecked exception, the first attempt to initialize the class will raise an ExceptionInInitializeError. Any subsequent attempts to use the class will cause a NoClassDefFoundError. If you really want to use an exception, throw something like a RuntimeException in the initializer.

However, the approach shown in the question—setting a flag when the class is initialized correctly—might actually be a better one for many applications. More specifically, I'd say that unless you want the whole program to terminate when there's a initialization failure, use a flag. Just remove the "throws" clause from the class declaration, because that isn't a legal syntax.

erickson
  • 265,237
  • 58
  • 395
  • 493
4

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 Faust
  • 12,396
  • 4
  • 50
  • 63
4

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
  • 37,814
  • 16
  • 84
  • 124
  • 1
    RuntimeException cannot be thrown from a static initialization block. You will get a compile error "Initializer does not complete normally". – Jonathon Faust Apr 13 '10 at 18:53
  • 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 Apr 13 '10 at 18:55
  • @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 Apr 13 '10 at 18:59
  • 2
    @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 Apr 13 '10 at 18:59
  • Jonathan, try the example I posted. – Amir Afghani Apr 13 '10 at 19:01
  • @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 Faust Apr 13 '10 at 19:02
  • 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 Apr 13 '10 at 19:06
0

You can't throw an exception in class definition. You should throw your exception in method definition or use try-catch block.

0

throwing a specific type of Exceptions will reduce bugs because the base class Exception can handle all the types of exceptions.

you can find more details here about types of exceptions in the link below : here

this will give you an idea about types of exceptions. PS : only methods can handle exceptions in java.

Minato
  • 21
  • 2