Question about Java exception handling

I have an abstract Java class with one (non-abstract) static method, e.g. like so:

Code:
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:

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

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

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

Anyone know how to fix this?

Thanks in advance,

Alphons
 
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:
Code:
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.
 
dap said:
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
 
Back
Top