Java: custom-exception-error

13,090

Solution 1

Working Code

Try this:

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:

  • Catching Error instead of Exception
  • Using a static method to construct the exception
  • Not extending Exception for your exception
  • Not calling the superclass constructor of Exception with the message

The posted code resolves those issues and displays what you were expecting.

Solution 2

TestExceptions.test returns type void, so you cannot throw it. For this to work, it needs to return an object of a type that extends Throwable.

One example might be:

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

However, this isn't very clean. A better pattern would be to define a TestException class that extends Exception or 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 package java.lang can be referenced by their class name rather than their fully-qualified name. That is, you don't need to write java.lang.)

Share:
13,090
hhh
Author by

hhh

Updated on June 27, 2022

Comments

  • hhh
    hhh almost 2 years
    $ 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() );
            }
        }
    }
    
  • danben
    danben about 14 years
    That's because String is not Throwable. See the second sentence of my answer.