error: incompatible types: NullPointerException cannot be converted to Throwable - nullpointerexception

I am trying to handle the NullPointerException. I am getting the following error after executing the .class file
NullPointerException.java:11: error: incompatible types: NullPointerException cannot be converted to Throwable
catch(NullPointerException e)
The code for the exception handling is
I caught the exception successfully when I write either catch(Exception e) or catch(Throwable e)
but writing catch(NullPointerException e) in code generating error. What could be the reason?
EDIT 1:
Code is as follows:
import java.lang.*;
public class NullPointerException
{
public static void main(String args[])
{
String s=null;
try
{
System.out.println(s.length());//NullPointerException
}
catch(NullPointerException e)
{
System.out.println("You are trying to print the null value of string causing ");
}
System.out.println("rest of the code...");
}
}

Related

ASP.NET Core Interception with Castle.DinamicProxy doesn't throw Exception with Async Methods !!! How can I solve this?

I have been creating a project with Aspect Oriented Programming paradigm and
I have an "ExceptionLogAspect" class attribute which is used on business methods to log the errors throwing from them.
public class ExceptionLogAspect : MethodInterception
{
private readonly LoggerServiceBase _loggerServiceBase;
private static byte _risk;
public ExceptionLogAspect(Type loggerService, byte risk)
{
if (loggerService.BaseType != typeof(LoggerServiceBase))
{
throw new System.Exception(AspectMessages.WrongLoggerType);
}
_loggerServiceBase = (LoggerServiceBase)Activator.CreateInstance(loggerService);
_risk = risk;
}
protected override void OnException(IInvocation invocation, System.Exception e)
{
var logDetailWithException = GetLogDetail(invocation);
logDetailWithException.ExceptionMessage = e.Message;
_loggerServiceBase.Error(logDetailWithException);
}
}
This Aspect migrates MethodInterception class that I created with Castle.DinamicProxy package. And OnException method included by MethodInterception logs the exception data.
public abstract class MethodInterception:MethodInterceptionBaseAttribute
{
protected virtual void OnBefore(IInvocation invocation){}
protected virtual void OnAfter(IInvocation invocation){}
protected virtual void OnException(IInvocation invocation, System.Exception e){}
protected virtual void OnSuccess(IInvocation invocation){}
public override void Intercept(IInvocation invocation)
{
var isSuccess = true;
OnBefore(invocation);
try
{
invocation.Proceed();//Business Method works here.
}
catch (Exception e)
{
isSuccess = false;
OnException(invocation, e);
throw;
}
finally
{
if(isSuccess)
OnSuccess(invocation);
}
OnAfter(invocation);
}
}
When I run the code and try-catch block doesn't work for Exception. So catch block isn't called and no messages are logged.
If I turn the business method into a syncronous method, exception will be thrown and data will be logged.
How can I solve this asynchronous method problem?
I tried this solution, it works properly.
Intercept method has to be like this to make this process asynchronous.
Otherwise, this method doesn't work properly for async.
There are some other ways, for example Castle CoreAsync Interceptor, you can find it on Github or NuGet.
https://github.com/JSkimming/Castle.Core.AsyncInterceptor
public override void Intercept(IInvocation invocation)
{
var isSuccess = true;
OnBefore(invocation);
try
{
invocation.Proceed(); //Metodu çalıştır
if (invocation.ReturnValue is Task returnValueTask)
{
returnValueTask.GetAwaiter().GetResult();
}
if (invocation.ReturnValue is Task task && task.Exception != null)
{
throw task.Exception;
}
}
catch (Exception e)
{
isSuccess = false;
OnException(invocation, e);
throw;
}
finally
{
if (isSuccess)
OnSuccess(invocation);
}
OnAfter(invocation);
}

Quarkus ExceptionMapper does not handle WebApplicationException

I'm trying to understand if this is a feature or a bug... :-)
For the below controller and exception mapper, for a rest client that will fail with a 401 response, I would expect the exception handler to be invoked for both cases. However it's not invoked for the WebApplicationException. Why is that and how are you meant to register an exception handler for them cases. This is using Quarkus version 0.21.2
#Path("/failable")
public class FailableResource {
#Inject
#RestClient
private SomeHttpClient httpClient;
#GET
#Path("fails")
#Produces(MediaType.TEXT_PLAIN)
public String fails() {
try {
return httpClient.someQuery();
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
#GET
#Path("works")
#Produces(MediaType.TEXT_PLAIN)
public String works() {
try {
return httpClient.someQuery();
} catch (Exception e) {
e.printStackTrace();
throw new IllegalStateException("Not a WebApplicationException");
}
}
}
And the ExceptionMapper
#Provider
public class HandleMySillyError implements ExceptionMapper<Throwable> {
#Override
public Response toResponse(Throwable e) {
e.printStackTrace();
return Response.ok("Some handled response").build();
}
}
I found out when running in quarkus:dev mode the exception mapper is not invoked. It seems that this is caused by an exception mapper from quarkus that is only used in DEV mode (see https://github.com/quarkusio/quarkus/issues/7883).
I launched my code local as normal a normal java program, causing my exception handler to work as expected. Also when running the code on Openshift, my custom exception mapper is used as well.
note: I used quarkus version 1.8.3

how to solve Test run failed: Instrumentation run failed due to 'Native crash' in robotium

I am trying JUnit test but facing following issue.
When I select Android JUnit Test by right clicking on Project it shows following message
Test run failed: Instrumentation run failed due to 'Native crash'
and when I right click on TestApk.java and select Android JUnit Test, it shows
Test run failed: Instrumentation run failed due to java.lang.ClassNotFoundException
Two cases occurs
Here is my source code.
#SuppressWarnings("unchecked")
public class TestApk extends ActivityInstrumentationTestCase2 {
private static final String LAUNCHER_ACTIVITY_FULL_CLASSNAME = "com.nhn.android.ndrive";
private static Class launcherActivityClass;
static {
try {
launcherActivityClass = Class
.forName(LAUNCHER_ACTIVITY_FULL_CLASSNAME);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
}
}
public TestApk() throws ClassNotFoundException {
super(launcherActivityClass);
}
private Solo solo;
#Override
protected void setUp() throws Exception {
super.setUp();
solo = new Solo(getInstrumentation(), getActivity());
}
public void testDisplayBlackBox() {
//Enter any integer/decimal value for first editfield, we are writing 10
solo.clickOnWebElement(By.id("com.nhn.android.ndrive:id/actionbar_photo_left_button"));
solo.clickOnWebElement(By.id("com.nhn.android.ndrive:id/gnb_group_layout"));
//Enter any integer/decimal value for first editfield, we are writing 20
solo.clickOnWebElement(By.id("com.nhn.android.ndrive:id/actionbar_open_drawer_button"));
//Click on Multiply button
solo.clickOnButton("com.nhn.android.ndrive:id/base_menu_task_open_button");
//Verify that resultant of 10 x 20
//assertTrue(solo.searchText("200"));
}
#Override
public void tearDown() throws Exception {
solo.finishOpenedActivities();
}
}
but package name is not wrong.
how to solve this problem?

Groovy compiler fails with unexpected token on readObject

My Gradle project has a mix of Java and Groovy classes. All source is under src/main/groovy. One of my Groovy classes contains a Map that I have created from reading a JSON string via JsonSlurper.parseText(). This class is marked Serializable.
To avoid a NotSerializableException, I have implemented my own writeObject() and readObject() methods, but my code is not compiling. I didn't find many Groovy examples, but various Java references and tutorials told me to use these signatures:
private void writeObject(java.io.ObjectOutputStream out)
throws IOException
private void readObject(java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException
My class looks like this:
import groovy.json.JsonBuilder
import groovy.json.JsonSlurper
class GroovyJSONMap implements Serializable {
private static final long serialVersionUID = 20150902L
Map myJSON = [:]
GroovyJSONMap() {
//no op
}
GroovyJSONMap(String json) {
if (json) {
try {
setJSON(json)
} catch (any) {
println "WHOOPS! Not a JSON object...."
myJSON = ["invalid": true]
}
}
}
GroovyJSONMap(Map json) {
if (json) {
setJSON(json)
}
}
final void setJSON(String json) {
myJSON = new JsonSlurper().parseText(json)
}
String getJSON() {
new JsonBuilder(myJSON).toString()
}
#Override
String toString() {
getJSON()
}
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
setJSON((String)in.readObject())
}
private void writeObject(ObjectOutputStream out) throws IOException {
out.writeObject(getJSON())
}
}
The compiler error:
:clean
:compileJava UP-TO-DATE
:compileGroovy
startup failed:
c:\path\to\src\main\groovy\GroovyJSONMap.groovy: 44: unexpected token: ObjectInputStream # line 110, column 29.
private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
^
1 error
:compileGroovy FAILED
I have moved the readObject() method to various positions in the source, but it still is not compiling. The compiler does not complain about writeObject(), only readObject(). Why is my code not compiling?
The compiler points to ObjectOutputStream, but the problem is really at in.
The word in is a reserved word in Groovy and cannot be used for a variable or method name.
The solution is to rename in to any non-Groovy-reserved word, such as stream (also changed writeObject() for consistency):
private void readObject(ObjectInputStream stream) throws IOException, ClassNotFoundException {
setJSON((String)stream.readObject())
}
private void writeObject(ObjectOutputStream stream) throws IOException {
stream.writeObject(getJSON())
}

Dealing with multiple JUnit test cases

I'm writing JUnit test cases using the selenium web driver, and I'm running into issues when trying to make multiple tests in one file. Here is an example of my code structure:
public class exampleScripts extends SeleneseTestCase {
public void setUp() throws Exception{
SeleniumServer seleniumServer = new SeleniumServer();
seleniumServer.start();
setUp("https://my.target.URL", *firefox");
}
#Test
public void test1() throws Exception {
//do test stuff
try {
//check if results are good
}
catch (Throwable e) {
//handle error
}
}
#Test
public void test2() throws Exception {
//do more test stuff
try {
//check results
}
catch (Throwable e) {
//handle error
}
}
}
Now, the tests by themselves work correctly, but I am getting the error Failed to start: SocketListener1#0.0.0.0:4444 when running my class as a whole. The first test runs correctly, but the second I move on to the next test, it seems like it's trying to re-start the session, when I just want it to continue on the old session. How do I get around this issue?
It seems I was able to find a wonky work-around for this problem, though I wouldn't recommend this to others as a solution. I created a test_suite function to run all my tests, and log the results myself.
public void setUp() {
//setUp stuff
}
public void testAll() throws Exception {
selenium.open("my/target/path");
test1();
test2();
}
#Test
public void test1() throws Exception {
//test stuff
try {
//check results
}
catch (Throwable e) {
log.INFO("There was an error in test1");
}
}
//and so on
The whole test suite would be run on testAll(). Again, would not recommend this solution, as it does not take advantage of JUnit's logging, but it worked for me.