How to throw RuntimeException (“cannot find symbol”)

后端 未结 9 1088
别跟我提以往
别跟我提以往 2021-02-03 18:47

I\'m trying to throw an exception in my code like this:

throw RuntimeException(msg);

But when I build in NetBeans I get this error:

<         


        
相关标签:
9条回答
  • 2021-02-03 19:16

    you will have to instantiate it before you throw it

    throw new RuntimeException(arg0) 
    

    PS: Intrestingly enough the Netbeans IDE should have already pointed out that compile time error

    0 讨论(0)
  • 2021-02-03 19:21

    Just for others: be sure it is new RuntimeException, not new RuntimeErrorException which needs error as an argument.

    0 讨论(0)
  • 2021-02-03 19:23

    As everyone else has said, instantiate the object before throwing it.

    Just wanted to add one bit; it's incredibly uncommon to throw a RuntimeException. It would be normal for code in the API to throw a subclass of this, but normally, application code would throw Exception, or something that extends Exception but not RuntimeException.

    And in retrospect, I missed adding the reason why you use Exception instead of RuntimeException; @Jay, in the comment below, added in the useful bit. RuntimeException isn't a checked exception;

    • The method signature doesn't have to declare that a RuntimeException may be thrown.
    • Callers of that method aren't required to catch the exception, or acknowlege it in any way.
    • Developers who try to later use your code won't anticipate this problem unless they look carefully, and it will increase the maintenance burden of the code.
    0 讨论(0)
  • 2021-02-03 19:26

    using new keyword we always create a instance (new object) and throwing it , not called a method

    throw new RuntimeException("Your Message");
    
    You need the new in there. It's creating an instance and throwing it, not calling a method.
    
    int no= new Scanner().nextInt();   // we crate an instance using new keyword and throwing it 
    

    using new keyword memory clean [because use and throw]

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
    
            //do your work here..
        }
    }, 1000);
    
    0 讨论(0)
  • 2021-02-03 19:27

    throw new RuntimeException(msg);

    You need the new in there. It's creating an instance and throwing it, not calling a method.

    0 讨论(0)
  • 2021-02-03 19:30
    throw new RuntimeException(msg); // notice the "new" keyword
    
    0 讨论(0)
提交回复
热议问题