Java: custom-exception-error

$ javac TestExceptions.java 
TestExceptions.java:11: cannot find symbol
symbol  : class test
location: class TestExceptions
            throw new TestExceptions.test("If you see me, exceptions work!");
                                    ^
1 error

      

code

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

public class TestExceptions {
    static void test(String message) throws java.lang.Error{
        System.out.println(message);
    }   

    public static void main(String[] args){
        try {
             // Why does it not access TestExceptions.test-method in the class?
            throw new TestExceptions.test("If you see me, exceptions work!");
        }catch(java.lang.Error a){
            System.out.println("Working Status: " + a.getMessage() );
        }
    }
}

      

+2


a source to share


2 answers


Working code

Try the following:

public class TestExceptions extends Exception {
    public TestExceptions( String s ) {
      super(s);
    }

    public static void main(String[] args) throws TestExceptions{
        try {
            throw new TestExceptions("If you see me, exceptions work!");
        }
        catch( Exception a ) {
            System.out.println("Working Status: " + a.getMessage() );
        }
    }
}

      

Problems



There are a number of issues with the code you posted, including:

  • Capture Error

    insteadException

  • Using a static method to throw an exception
  • Doesn't apply Exception

    to your exception
  • Don't call superclass constructor Exception

    with message

The published code resolves these issues and displays what you expected.

+3


a source


TestExceptions.test

returns a type void

, so you can't throw

. For this to work, it needs to return an object of the type that extends Throwable

.

One example might be:

   static Exception test(String message) {
        return new Exception(message);
    } 

      



However, this is not very clean. A better pattern would be to define a class TestException

that extends Exception

either RuntimeException

or Throwable

, and then just throw

that.

class TestException extends Exception {
   public TestException(String message) {
     super(message);
   }
}

// somewhere else
public static void main(String[] args) throws TestException{
    try {
        throw new TestException("If you see me, exceptions work!");
    }catch(Exception a){
        System.out.println("Working Status: " + a.getMessage() );
    }
}

      

(Also note that all classes in a package java.lang

can refer to their class name rather than their fully qualified name. That is, you don't need to write java.lang

.)

+5


a source







All Articles