NullPointerException with lambda expression - working with loops - eclipse

I have 2 pieces of codes, one written with the java old style and the other is written with lambda expression,
The first:
Class enumClass = getConstantsEnum();
Object[] enumConstants = enumClass.getEnumConstants();
for(Object o:enumConstants) {
try {
constantsMap.put(o.toString(),o.getClass().getDeclaredField("lookupValue").getInt(o));
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
| SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
Is working fine and filling the map correctly
The other:
Class enumClass = getConstantsEnum();
Object[] enumConstants = enumClass.getEnumConstants();
constantsMap.putAll(Arrays.asList(enumConstants)
.stream().collect(Collectors.toMap
(e -> e.toString(), e -> {
try {
return e.getClass().getDeclaredField("lookupValue").getInt(e);
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
| SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}finally {
return null;
}
}
)));
Is giving null pointer exception, though by debugging the line e.getClass().getDeclaredField("lookupValue").getInt(e) I see it gets filled by value
My questions are:
1-what is wrong with this code?
2- how can I debug effectively inside stream methods in eclipse, is there a way to see elements getting populated inside the map one by one as in normal loop ? I could see the first element by putting a breakpoint but then the exceptions is fired immediately
3- is there a cleaner way to handle the exception inside the lambda expression, I tried wrapping the whole code with try/catch but compiler is still complaining that the exception is not handled.
Answer to any question is appreciated :)
EDIT:
Q1 answered by Holger in comments
IDE added

As stated in comment posted by Holger in comment, you can see that there is known bug in Java 8, with unresolved status, because of which you cannot put null values using Collectors.toMap, see issue here: https://bugs.openjdk.java.net/browse/JDK-8148463
Intellij IDEA has a great support for debugging Java 8 streams. Check this article: https://www.baeldung.com/intellij-debugging-java-streams
No, there currrently isn't, or I don't know about it. My suggestion for improving your code is to extract a method where you can handle your exception:
constantsMap.putAll(Arrays.asList(enumConstants)
.stream().collect(
Collectors.toMap(e -> e.toString(),
this::getInteger
)));
}
private Integer getInteger(Object e) {
try {
return e.getClass().getDeclaredField("lookupValue").getInt(e);
} catch (IllegalArgumentException | IllegalAccessException | NoSuchFieldException
| SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} finally {
return null;
}
}

Related

Flutter and Dart try catch—catch does not fire

Given the shortcode example below:
...
print("1 parsing stuff");
List<dynamic> subjectjson;
try {
subjectjson = json.decode(response.body);
} on Exception catch (_) {
print("throwing new error");
throw Exception("Error on server");
}
print("2 parsing stuff");
...
I would expect the catch block to execute whenever the decoding fails. However, when a bad response returns, the terminal displays the exception and neither the catch nor the continuation code fires...
flutter: 1 parsing stuff
[VERBOSE-2:ui_dart_state.cc(148)] Unhandled Exception: type
'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type
'List<dynamic>'
What am I missing here?
Functions can throw anything, even things that aren't an Exception:
void foo() {
throw 42;
}
But the on Exception clause means that you are specifically catching only subclass of Exception.
As such, in the following code:
try {
throw 42;
} on Exception catch (_) {
print('never reached');
}
the on Exception will never be reached.
It is not a syntax error to have on Exception catch as someone else answered. However you need to be aware that the catch will not be triggered unless the error being thrown is of type Exception.
If you want to find out the exact type of the error you are getting, remove on Exception so that all errors are caught, put a breakpoint within the catch and check the type of the error. You can also use code similar to the following, if you want to do something for Exceptions, and something else for errors of all other types:
try {
...
} on Exception catch (exception) {
... // only executed if error is of type Exception
} catch (error) {
... // executed for errors of all types other than Exception
}
Use:
try {
...
} on Exception catch (exception) {
... // only executed if error is of type Exception
} catch (error) {
... // executed for errors of all types other than Exception
}
The rule is that exception handling should be from detailed exceptions to general exceptions in order to make the operation to fall in the proper catch block and give you more information about the error, like catch blocks in the following method:
Future<int> updateUserById(int userIdForUpdate, String newName) async {
final db = await database;
try {
int code = await db.update('tbl_user', {'name': newName},
whereArgs: [userIdForUpdate], where: "id = ?");
return code;
}
on DatabaseException catch(de) {
print(de);
return 2;
}
on FormatException catch(fe) {
print(fe);
return 2;
}
on Exception catch(e) {
print(e);
return 2;
}
}
print("1 parsing stuff");
List<dynamic> subjectjson;
try {
subjectjson = json.decode(response.body);
} catch (_) { . // <-- removing the on Exception clause
print("throwing new error");
throw Exception("Error on server");
}
print("2 parsing stuff");
...
This works, but what is the rationale behind this? Isn't the type inconsistency an Exception?
As everybody or most of the people said, try to know exactly what error you are getting:
try{
}
catch(err){
print(err.runTimeType);
}
runTimeType will give you the type of data or exception you are getting or to put simple the exception itself.
And then do whatever you want. (Like if you are not getting the exception of what you expected, then try to fix that issue or change the exception.)
Another option is to go with general form.
Using the simple catch which will prompt every time.
The other possible reason for the catch bloc not to fire, as pointed out in this question, is missing brackets when throwing an exception.
Must write throw FormatException() instead of throw FormatException.
I had a issue with try catch but my problem was the API that I send http request, doesn't response of my request so that is why my request doesn't response anything and try catch didn't catch the error. So I suggest you to add timeout to your request so that if your api doesn't response your request after a while you can cancel your request with timeout. Here is an example how to use it;
try {
final response = await http.post(Url).timeout(Duration(seconds: 5));
} catch (error) {
print(error)
}

spark catch all exception and print to to string

I have some spark code, I need to catch all exception and store to file for some reason, so I tried to catch the exception and print it but its print empty
try {
/* Some spark code */
}
catch {
case e: Exception => {
println(" ************** " + e.printStackTrace())
}
}
output currently printing nothing ************** ()
printStackTrace doesn't return a stacktrace. It just prints it into the stderr. If you want to store it in the file you can
a) call e.getStackTrace and save each element manually
b) call e.printStackTrace(s) where s is a PrintStream or a PrintWriter pointing to your output file.
[Please find below the link that has answer to query][1]
Scala: Silently catch all exceptions

Multiple exception catch block java 8 eclipse

I'm getting an unhandled message exception for IOException. As you can see in the pasted code I've handled the IOException. The JDK for both eclipse & the project is Java 8 update 121 so I know catching multiple exceptions is supported. What am I doing wrong?
try (InputStream inputStream = BatchMessageProperties.class.getClassLoader().
getResourceAsStream(propertiesFileName)) {
load(inputStream);
//need to make sure all properties are present & not null.
validate(this);
} catch (IOException | InvalidBatchMessagePropertiesFileException ex) {
logger.error(ex.getLocalizedMessage());
ex.printStackTrace();
throw ex;
}
You do rethrow ex inside your catch block, which may be an IOException, right?

Check Existence of a folder using Dropbox SDK

In Dropbox SDK 2.0, is there a way to check the existence of a folder? Or do we use the brute force method of listing the folders and then scanning the list?
You can use the /2/files/get_metadata endpoint to check for an existing folder at a given path. It will either return the metadata if it exists, or a path.not_found error if not.
You didn't mention which SDK you're referring to, but for example, in the Dropbox API v2 Java SDK, that corresponds to the DbxUserFilesRequests.getMetadata method.
Here is the complete Java code to check for existence of a folder and create if folder does not exist
DbxClientV2 dbxClient;
try
{
dbxClient.files().getMetadata("/MyFolder");
}
catch (GetMetadataErrorException e)
{
// TODO Auto-generated catch block
if (e.errorValue.isPath())
{
LookupError le = e.errorValue.getPathValue();
if (le.isNotFound())
{
System.out.println("Path doesn't exist on Dropbox: ");
try
{
dbxClient.files().createFolder("/MyFolder");
}
catch (CreateFolderErrorException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
catch (DbxException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
}
}

method retuns error code or what is the best way to do that

i have a class like this:
class myclass {
public function save($params){
// some operations
// posible error
return false;
// some more code
// posible error
return false;
// more code
// if everything is ok
return true;
}
}
but what is the best way to display errors, one idea is make the class return numbers like for example:
public function save($params) {
// some operations
// some error with the db
return 1;
// more code
// some error with a table
retunr 2;
// more code
// if everything is ok
return 0;
}
and when al call this function, make a switch in order to display the errors:
$obj = new myclass();
$err = $obj->save($params);
switch($err) {
case 1: echo 'error with the db'; break;
case 2: echo 'error with some table'; break;
default: echo 'object saved!';
}
is this the best way to write this? or there is another way?
Many programming languages give you the option to throw and catch exceptions. Where available, this is generally a better error handling model.
public function save($params) throws SomeException {
// some operations
if (posible error)
throw new SomeException("reason");
}
// client code
try {
save(params);
} catch (SomeException e) {
// log, recover, abort, ...
}
Another advantage of Exceptions is that they will (at least in some languages) give you access to stack trace as well as message.