I have this class:
public class SomeClass {
public void someMethod() {} throws someException
public class someException extends Exception { // Exception class
public someException(String message) {
super(message);
}
}
}
Another class:
public class SomeOtherClass {
public static void main (String[] args) {
SomeClass obj = new SomeClass();
try {
obj.someMethod();
} catch (someException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Eclipse complains that "someException cannot be resolved to a type". I tried to add
import SomeClass.someException
But then it says "The import SomeClass cannot be resolved"
You could of course put someException in a separate file, and not make it nested, is this the only way?
You should be able to use the class by qualifying it with the class name, SomeClass.someException. If you'd rather import it, you have to put your code in a package. You can then do:
import yourpkg.SomeClass.someException;
Also, you got the syntax a bit wrong here:
public void someMethod() {} throws someException
it should be
public void someMethod() throws someException {}
(But perhaps that was a typo in your question.)
You may also want to consider making the nested class static unless you really need to reference the enclosing object:
public static class someException extends Exception {
...
}
Related
I'm trying to define my own exception class the easiest way, and this is what I'm getting:
public class MyException extends Exception {}
public class Foo {
public bar() throws MyException {
throw new MyException("try again please");
}
}
This is what Java compiler says:
cannot find symbol: constructor MyException(java.lang.String)
I had a feeling that this constructor has to be inherited from java.lang.Exception, isn't it?
No, you don't "inherit" non-default constructors, you need to define the one taking a String in your class. Typically you use super(message) in your constructor to invoke your parent constructor. For example, like this:
public class MyException extends Exception {
public MyException(String message) {
super(message);
}
}
A typical custom exception I'd define is something like this:
public class CustomException extends Exception {
public CustomException(String message) {
super(message);
}
public CustomException(String message, Throwable throwable) {
super(message, throwable);
}
}
I even create a template using Eclipse so I don't have to write all the stuff over and over again.
If you use the new class dialog in Eclipse you can just set the Superclass field to java.lang.Exception and check "Constructors from superclass" and it will generate the following:
package com.example.exception;
public class MyException extends Exception {
public MyException() {
// TODO Auto-generated constructor stub
}
public MyException(String message) {
super(message);
// TODO Auto-generated constructor stub
}
public MyException(Throwable cause) {
super(cause);
// TODO Auto-generated constructor stub
}
public MyException(String message, Throwable cause) {
super(message, cause);
// TODO Auto-generated constructor stub
}
}
In response to the question below about not calling super() in the defualt constructor, Oracle has this to say:
Note: If a constructor does not explicitly invoke a superclass constructor, the Java compiler automatically inserts a call to the no-argument constructor of the superclass.
Reason for this is explained in the Inheritance article of the Java Platform which says:
"A subclass inherits all the members (fields, methods, and nested
classes) from its superclass. Constructors are not members, so they
are not inherited by subclasses, but the constructor of the superclass
can be invoked from the subclass."
package customExceptions;
public class MyException extends Exception{
public MyException(String exc)
{
super(exc);
}
public String getMessage()
{
return super.getMessage();
}
}
import customExceptions.MyException;
public class UseCustomException {
MyException newExc=new MyException("This is a custom exception");
public UseCustomException() throws MyException
{
System.out.println("Hello Back Again with custom exception");
throw newExc;
}
public static void main(String args[])
{
try
{
UseCustomException use=new UseCustomException();
}
catch(MyException myEx)
{
System.out.println("This is my custom exception:" + myEx.getMessage());
}
}
}
Exception class has two constructors
public Exception() -- This constructs an Exception without any additional information.Nature of the exception is typically inferred from the class name.
public Exception(String s) -- Constructs an exception with specified error message.A detail message is a String that describes the error condition for this particular exception.
If you inherit from Exception, you have to provide a constructor that takes a String as a parameter (it will contain the error message).
and don't forget the easiest way to throw an exception (you don't need to create a class)
if (rgb > MAX) throw new RuntimeException("max color exceeded");
I'm learning java reflection. I am using the following code. But when I run, it gives the error
unreported exception ClassNotFoundException; must be caught or
declared to be thrown
Class className=Class.forName("First");
Maybe I'm going wrong somewhere. Please help me out. Here's the code:
import java.lang.reflect.Method;
public class First{
public void print(){}
public void ready(){}
}
public class test{
public static void main(String args[])
{
Class className=Class.forName("com.Test.First");
Method[] methods=className.getMethods();
System.out.println("First method is" + methods[0]);
}
}
All it's saying is that Class.forName throws this (non-runtime) Exception so you must handle it somehow. Here are two ways you could do it
public class test{
public static void main(String args[]) throws ClassNotFoundException
{
Class className=Class.forName("com.Test.First");
Method[] methods=className.getMethods();
System.out.println("First method is" + methods[0]);
}
}
Or
public class test{
public static void main(String args[])
{
try {
Class className=Class.forName("com.Test.First");
Method[] methods=className.getMethods();
System.out.println("First method is" + methods[0]);
}
catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
}
}
This line is the problem
Class className=Class.forName("com.Test.First");
in the Class.forName("com.Test.First"), you can replace com.Test.First with any gibberish and the compiler shouldn't care enough to validate it for you. All the compiler knows is that it is possible for there to not be a class com.Test.First and therefore you are responsible for handling a ClassNotFoundException.
I have tracked down an error to line 362 of the java.lang.Class class:
Constructor<T> tmpConstructor = cachedConstructor;
The variable does not seem to get assigned. In the debug expression windows it only says "tmpConstructor cannot be resolved to a variable". The cachedConstructor is not null.
An error is only thrown further down when a the newInstance() function is called:
try {
return tmpConstructor.newInstance((Object[])null);
} catch (InvocationTargetException e) {
Unsafe.getUnsafe().throwException(e.getTargetException());
// Not reached
return null;
}
Context:
Using JSON Plugin with the Struts2 framework to create Java objects from the received JSON.
The field it is trying to parse is a subclass of an abstract class.
On further inspection (thanks to user902838) I was missing that it can't instantiate an abstract class. So I need to find out how it can instantiate subclasses, which is a different question.
Can someone please explain to me why the tmpconstructor is empty?
It's hard to tell without any information about the class you're trying to instantiate or the exception/error you observe, but my best guess would be that the class does not have a nullary constructor. This program exhibits such a problem:
package example;
public class NewInstanceTest {
public NewInstanceTest(String s) {
}
public static void main(String[] args) throws Exception {
Class.forName("example.NewInstanceTest").newInstance();
}
}
The problem can be fixed by adding a nullary constructor:
package example;
public class NewInstanceTest {
/* nullary constructor: */
public NewInstanceTest() {
this("default");
}
public NewInstanceTest(String s) {
}
public static void main(String[] args) throws Exception {
Class.forName("example.NewInstanceTest").newInstance();
}
}
or by removing all non-nullary constructors so that Java will provide a nullary one automatically:
package example;
public class NewInstanceTest {
public static void main(String[] args) throws Exception {
Class.forName("example.NewInstanceTest").newInstance();
}
}
I read this code where the interface throws an exception, but the class which implements it doesn't throw one or catch one, why is that? Is it legal or safe in java?
import java.rmi.*;
public interface MyRemote extends Remote {
public String sayHello() throws RemoteException;
}
import java.rmi.*;
import java.rmi.server.*;
public class MyRemoteImpl extends UnicastRemoteObject implements MyRemote{
public String sayHello() {
return "Server says, 'Hey'";
}
public MyRemoteImpl() throws RemoteException {}
public static void main (String[] args) {
try {
MyRemote service = new MyRemoteImpl();
Naming.rebind("RemoteHello", service);
} catch(Exception ex)
{
ex.printStackTrace();
}
}
}
A general rule of implementing and extending is you can make your new class or interface "less restrictive" but not "more restrictive". If you think of the requirement to handle an exception as a restriction, an implementation that doesn't declare the exception is less restrictive. Anybody who codes to the interface will not have trouble with your class.
— Stan James
As part of the discussion at http://www.coderanch.com/t/399874/java/java/Methods-throwing-Exception-Interface
If a Java method overrides another in a parent class, or implements a method defined in an interface, it may not throw additional checked exceptions, but it may throw fewer.
public class A {
public void thrower() throws SQLException {...}
}
public class B extends A {
#Override
public void thrower() throws SQLException, RuntimeException, NamingException {...}
}
SQLException is fine; it's declared in the overridden method. It could even be replaced by a subclass like SerialException.
RuntimeException is fine; those can be used anywhere.
NamingException is illegal. It isn't a RuntimeException, and isn't in A's list, even as a subtype.
Great answer by #Chetter Hummin.
One way to look at this, and I find it easy to remember, is interface's implementations can be more specific but not more general.
For example in interface void test() throws Exception means "test may throw exception"
then implementation can be void test() means "test will not throw exception" (more specific)
or implementation can be void test() throws NullpointerException (more specific)
interface x {
void testException() throws Exception;
}
public class ExceptionTest implements x {
#Override
public void testException() { //this is fine
}
////// or
#Override
public void testException() throws NullPointerException { // this is fine
}
}
I don't understand why the compiler does not warn me about not catching or throwing an SQLException. Here's the situation:
I have defined this interface:
public interface GenericDatabaseManager {
public void createTables(DataBase model) throws SQLException;
}
Then I created this class that implements the given interface:
public class SqliteHelper extends SQLiteOpenHelper implements
GenericDatabaseManager {
#Override
public void createTables(DataBase model) throws SQLException {
// Code that throws SQLException
}
And finally I'm calling this SqliteHelper.createTables() from here:
public class DatabaseManager extends CoreModule {
private boolean createUpdateDB(final String dbString, final String appId) {
// Previous code...
if (oldVer == -1) {
dbCoreModel.addModel(dbModel);
dbCoreModel.getManager().createTables(dbModel);
return true;
}
// More code...
}
}
dbCoreModel.getManager() returns a GenericDatabaseManager instance. But the compiler shows no error on dbCoreModel.getManager().createTables(dbModel); line, although this line throws an SQLException.
Does anyone have an idea about why is this happening? Thanks in advance.
EDIT: about SQLException does not need to be catched because it's a RuntimeException. This is not true. Here's an example:
import java.sql.SQLException;
interface Interface {
public void throwsSQLException() throws SQLException;
}
class Test implements Interface {
#Override
public void throwsSQLException() throws SQLException {
throw new SQLException();
}
}
public class Main {
public static void main(String[] args) {
Interface i = new Test();
i.throwsSQLException();
System.out.println("Finished");
}
}
The compiler DOES show an error in i.throwsSQLException(); in this case.
android.database.SQLException is a runtime exception.
In java it is not necessary to catch or declare throws for runtime exceptions. Read a detailed description about RuntimeExceptions in java here