Java / Android: How to work with return type 'List<MyType>'?-Collection of common programming errors
My problem is about Java / Android :
I created a class MyClass
which has a method getAllData()
that returns an List = new ArrayList()
. In an other class MyOtherClass
I call to this method and want to write the returned List into another List
.
But I get the following error: Unhandled exception type Exception
What can I do about this?
Here’s the code:
MyClass.java
public List datas = new ArrayList();
public List getAllData() throws Exception{
//add some things to datas...
return datas;
}
MyOtherClass.java
public void fetchData(){
MyClass mydatas = new MyClass();
List thedatas = mydatas.getAllData();
}
How can I solve the problem? With an “try / catch(Exception e)” surrounding the statement, it seems not to get the returned List from getAllData();
Thanks a lot in advance!
-
Since
getAllData()
might throws a checked exception (i.e., an exception that is not aRunTimeException
), you have to surround the statement withtry-catch
public void fetchData() { MyClass mydatas = new MyClass(); try { List thedatas = mydatas.getAllData(); } catch (Exception ex) { // display or log exception name } }
Or add
throws
clause after the method name.public void fetchData() throws Exception { MyClass mydatas = new MyClass(); List thedatas = mydatas.getAllData(); }
-
You declare the
getAllData
method to throwException
. The compiler is now asking you what to do if an exception of type Exception is thrown.You should NEVER throw
Exception
as part of a method signature. It is too general. Instead you should try to throw only the specific exceptions that may occur.If you do not wish
fetchData
to have to deal with exceptions then you must either declarefetchData
to throw the same exceptions OR makegetAllData
catch the exceptions and return an appropriate value if an exception is thrown.
Originally posted 2013-12-02 21:11:01.