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);
    }
}

6 Answers 6

44

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

Sign up to request clarification or add additional context in comments.

1 Comment

THANK YOU! No one mentions this.
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.

1 Comment

What you can then do is have each method in the DirReader class throw an exception if it failed to initialize correctly.
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);        
    }


}

7 Comments

RuntimeException cannot be thrown from a static initialization block. You will get a compile error "Initializer does not complete normally".
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).
@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
@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.
Jonathan, try the example I posted.
|
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.

Comments

0

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

Comments

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.