PDA

View Full Version : [Solved] Question about Java exception handling


fonz
March 17th, 2009, 17:37
I have an abstract Java class with one (non-abstract) static method, e.g. like so:

public abstract class Foo
{
public abstract void bar();

public static void feep()
{
// actual code here
}
}

So far, so good. This works. But now for the punchline: I would like to be able to have the function feep() able to throw an exception, but simply doing the following (changes highlighted) doesn't work:

public abstract class Foo
{
public abstract void bar();

public static void feep() throws SomeException
{
// actual code here
if(something)
throw new SomeException("whatever");
}
}

This results in a compiler error non-static variable this cannot be referenced from a static context with a mark at the beginning of new.

Anyone know how to fix this?

Thanks in advance,

Alphons

dap
March 17th, 2009, 21:25
Hello,

I don't know much about Java but I have the impression that the problem doesn't come from the fact that the class is abstract. This code compiles and runs fine, for example:
public abstract class Forums
{
public static void
spam()
throws SomeException

{
throw new SomeException();
}

public static void
main(String[] args)
{
try
{
spam();
}
catch (Exception e)
{
System.err.println(e);
}
}
}

class SomeException
extends Exception
{
}

The error message looks like you are referring to an attribute somewhere in a static method.

fonz
March 17th, 2009, 21:41
I have the impression that the problem doesn't come from the fact that the class is abstract.

Partially, it does.

Thing is (which I forgot to mention) that the SomeException class was defined as an inner class of the static class Foo. After having seen your example I moved the SomeException class out of the static class and into its own file and that solved the problem: the code now compiles just fine.

Thanks,

Alphons