GenericJDBCException catched by wrong part of the try/catch block - java

I have this block of code:
} catch (HibernateException e) {
loginAnswer = new LoginCustomerAreaAnswer(999);
//This function use the error code save inside loginAnswer
this.logOp.error(logsUtilities.logException(e, "HibernateException"));
} catch (Exception e) {
loginAnswer = new LoginCustomerAreaAnswer(997);
//This function use the error code save inside loginAnswer
this.logOp.error(logsUtilities.logException(e, "Exception"));
} finally {
return loginAnswer;
}
As you can see, I catch first the HibernateException type exception and then the generic Exception.
But when I look into the log file, when I have a org.hibernate.exception.GenericJDBCException exception it is catched like a generic Exception!
Why?, GenericJDBCException it is not "a son" of HibernateException? Would not have to be catched by the HibernateException??
This is an example of my log file
2013-05-21 11:01:02 [Level: ERROR]*** Exception: Error code: 997 - Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection
I really lost with this, can somebody help me?

Most probably you caught the Spring Exception:
org.springframework.transaction.CannotCreateTransactionException: Could not open Hibernate Session for transaction; nested exception is org.hibernate.exception.GenericJDBCException: Cannot open connection

I believe the problem is your constructor:
new LoginCustomerAreaAnswer(...)
With passed value 997.
Running this code:
public class Test
{
public static void main( String[] args )
{
try
{
throw new GenericJDBCException( "I'm dead", new SQLException() );
} catch ( HibernateException hex )
{
System.err.println( "HibernateException" );
hex.printStackTrace();
} catch ( Exception ex )
{
System.err.println( "Exception" );
ex.printStackTrace();
}
}
}
Gives me, as expected, HibernateException:
HibernateException
org.hibernate.exception.GenericJDBCException: I'm dead
at com.execon.utils.Test.main(Test.java:19)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
at java.lang.reflect.Method.invoke(Method.java:597)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:120)
Caused by: java.sql.SQLException
... 6 more

Related

Apache Kafka throws exceptions inside a try block{} catch

I'm having a problem that I'm not understanding very well, because although I understand the error I'm getting, what I don't understand is why it keeps throwing the exception if I'm supposed to be inside a try{}.
try{
Battle battleDto = om.readValue(battleObject.toString(), Battle.class);
try {
battleDto.setStarPlayer(battleObject.getJSONObject("starPlayer").getString("tag"));
return battleDto;
}catch (StreamsException e) {
log.error("No starPlayer for battleTime: " + battleDto.getBattletime());
return battleDto;
}
}catch (JsonProcessingException e ){
return null;
}
The exception occurs when accessing the "StarPlayer" field.
If someone could tell me why it keeps crashing I would appreciate it, as I think there is something very basic that I am not seeing.
Exception in thread "DataTreatment-b3211938-89f1-4cc0-83e8-0e4266286ed5-StreamThread-1" org.apache.kafka.streams.errors.StreamsException: Exception caught in process. taskId=0_0, processor=KSTREAM-SOURCE-0000000000, topic=battles, partition=0, offset=0, stacktrace=java.lang.NullPointerException: Cannot invoke "com.datatreatment.bsanalyst.controller.dao.entity.BattleDao.getBattleTime()" because "battleDao" is null
at com.datatreatment.bsanalyst.application.service.BattleDaoService.updateDatabase(BattleDaoService.java:26)
at com.datatreatment.bsanalyst.controller.listener.BattleListener.lambda$updateDatabase$0(BattleListener.java:59)
at org.apache.kafka.streams.kstream.internals.KStreamPeek$KStreamPeekProcessor.process(KStreamPeek.java:42)
at org.apache.kafka.streams.processor.internals.ProcessorAdapter.process(ProcessorAdapter.java:71)
at org.apache.kafka.streams.processor.internals.ProcessorNode.lambda$process$2(ProcessorNode.java:181)
at org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.maybeMeasureLatency(StreamsMetricsImpl.java:883)
at org.apache.kafka.streams.processor.internals.ProcessorNode.process(ProcessorNode.java:181)
at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forwardInternal(ProcessorContextImpl.java:273)
at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:252)
at org.apache.kafka.streams.processor.internals.ProcessorContextImpl.forward(ProcessorContextImpl.java:219)
at org.apache.kafka.streams.processor.internals.SourceNode.process(SourceNode.java:86)
at org.apache.kafka.streams.processor.internals.StreamTask.lambda$process$1(StreamTask.java:701)
at org.apache.kafka.streams.processor.internals.metrics.StreamsMetricsImpl.maybeMeasureLatency(StreamsMetricsImpl.java:883)
at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:701)
at org.apache.kafka.streams.processor.internals.TaskManager.process(TaskManager.java:1105)
at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:658)
at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:564)
at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:523)
at org.apache.kafka.streams.processor.internals.StreamTask.process(StreamTask.java:718)
at org.apache.kafka.streams.processor.internals.TaskManager.process(TaskManager.java:1105)
at org.apache.kafka.streams.processor.internals.StreamThread.runOnce(StreamThread.java:658)
at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:564)
at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:523)
Caused by: java.lang.NullPointerException: Cannot invoke "com.datatreatment.bsanalyst.controller.dao.entity.BattleDao.getBattleTime()" because "battleDao" is null
at com.datatreatment.bsanalyst.application.service.BattleDaoService.updateDatabase(BattleDaoService.java:26)
at com.datatreatment.bsanalyst.controller.listener.BattleListener.lambda$updateDatabase$0(BattleListener.java:59)
Thank you very much in advance

Difference between Exception and SQLException

Can someone explain the difference between catching an Exception and catching an SQLException? I know that SQLException will print out more information if you choose to print out the exception errors, but is there anything else?
try {
//code
} catch(Exception ex) {
//code
}
And
try {
//code
} catch(SQLException ex) {
//code
}
What are the benefits and differences of using Exception and SQLException in the catch block?
This is not the only difference.
Catching Exception is dangerous because it also catches all RuntimeExceptions (therefore unchecked exceptions), and that include niceties such as NullPointerException etc which are clear programmer errors. Don't do that!
Also, Exception is a class like any other, so you can subclass it and add constructors/methods of yours. For instance, SQLException has a .getErrorCode() method which Exception does not have. If you only catch Exception, you cannot access this method.
In general, catching the "more precise" exception first is the best. For instance, with the new (in Java 7...) file API, you can easily distinguish between filesystem level errors and other I/O errors, since FileSystemException extends IOException:
try {
something();
} catch (FileSystemException e) {
// fs level error
} catch (IOException e) {
// I/O error
}
It's all about the hierarchy,when you are talking about the catching the exception.
Technically speaking, Exception - is the super class which catches each and every exception.
If you are writing something related to SQL in the try block and you know it may even throw SQL Exception.
Then you may declare it this way as well.
try
{
}catch(SQLException ex)
{
Do this,when SQL Exception is caught.
}
catch(Exception ex)
{
Generic Exception - works for all
}
SQLException inherits from Exception, so SQLException will contain more (and more specific) information than Exception (which is intended to apply generally to all exceptions).
You can also have multiple catch clauses; so you can first try to catch the SQLException, but if it's not a SQLException, then you can just catch the general Exception.
In general, you shouldn't catch exceptions unless you intend to handle them in some way. You can have a top-level exception handler that catches any exceptions that bubble up to the top of the call stack, so that your program doesn't crash on unhandled exceptions.
A - Explanation
SQLException is a subtype of java.lang.Exception and also it is implementing the Iterable<Throwable> class. Programmers prefer throwing different subtypes of Exception class because on some higher level, they want to catch the exact sub-Exception class so that they can be sure that that specific Exception is thrown on some exact scenario. Thus, they can know the exact source of Exception.
B - Example
Consider you have written a method that throws multiple exceptions. Let's say, you take a json String and parse it, then persist it on the database. Consider the following method;
public boolean persistCustomer(String jsonString) throws SQLException, IOException {
Connection conn = getConnection();
PreparedStatement preparedStatement = null;
ObjectMapper objectMapper = new ObjectMapper();
try {
Customer customer = objectMapper.readValue(jsonString, Customer.class);
preparedStatement = conn.prepareStatement(PERSIST_CUSTOMER);
preparedStatement.setString (1, customer.getName());
preparedStatement.setInt (2, customer.getAge());
preparedStatement.setBoolean (3, customer.getIsRegular());
preparedStatement.executeUpdate();
return true;
} catch (IOException e) {
throw e;
} finally {
try {
if (preparedStatement != null)
preparedStatement.close();
if (conn != null)
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
In this method, we are converting JSON into a Customer class and also we persist customer class to the database.
The following lines throw SQLException;
preparedStatement = conn.prepareStatement(PERSIST_CUSTOMER);
preparedStatement.setString (1, customer.getName());
preparedStatement.setInt (2, customer.getAge());
preparedStatement.setBoolean (3, customer.getIsRegular());
preparedStatement.executeUpdate();
prepareStatement(), setters and executeUpdate() methods, all of them throwing SQLException's. But also, the line that which we convert JSON in a String into a Customer object, also throws several Exceptions other than SQLException.
Customer customer = objectMapper.readValue(jsonString, Customer.class);
readValue() method throws JsonParseException, JsonMappingException and also IOException. All of them can be catched using an IOException because the JSON related exceptions extend IOException.
I'm going to provide two different examples so that it will be obvious to understand why we need different types of Exceptions.
C - Bad Practice: Using Exception To Catch All Exceptions
public class BadPracticeExample {
public static void main(String[] args) {
MySQLUtil dbUtil = new MySQLUtil();
String jsonString = "{\"name\":\"Levent\",\"age\":31,\"isRegular\":true}";
try {
dbUtil.persistCustomer(jsonString);
} catch (Exception e) {
System.out.println("A problem occured");
}
}
}
As you can see, it catches the Exception but what are we going to do if we need special exception handling for two different sources of problems? persistCustomer can throw either IOException or an SQLException and what if we need to do different set of tasks to handle those problems? I want to send an email to the database admin when an SQLException occurs and I want to continue when a JSON parsing problem occurs, on the case that an IOException is catched?
In this scenario you can't do that. Here is the output of the code snippet above and we are only sure that an Exception occured but we don't have any idea about what is the source of it;
A problem occured
D - Good Practice Example I: SQL Exception catched
public class GoodPracticeExample {
public static void main(String[] args) {
MySQLUtil dbUtil = new MySQLUtil();
String jsonString = "{\"name\":\"Levent\",\"age\":31,\"isRegular\":true}";
try {
dbUtil.persistCustomer(jsonString);
} catch (SQLException e) {
System.out.println("SQL Exception catched, SQL State : " + e.getSQLState());
System.out.println("Error Code : " + e.getErrorCode());
System.out.println("Error Message : " + e.getMessage());
} catch (IOException e) {
System.out.println("Cannot parse JSON : " + jsonString);
System.out.println("Error Message : " + e.getMessage());
}
}
}
As you can see, we catch for both, JSON and SQL problem and in this example, submethod is trying to persist DB where there is no table. The output is as below;
SQL Exception catched, SQL State : 42000
Error Code : 1142
Error Message : INSERT command denied to user 'levent'#'example.com' for table 'CUSTOMER'
So we have catched SQL Exception and we have all parameters we need to send an alarm email. We can add additional handler or utility methods on the SQLException catch block.
D - Good Practice Example II: IOExceptoin catched on Parsing Error
public class GoodPracticeExample {
public static void main(String[] args) {
MySQLUtil dbUtil = new MySQLUtil();
String jsonString = "{\"Zname\":\"Levent\",\"age\":31,\"isRegular\":true}";
try {
dbUtil.persistCustomer(jsonString);
} catch (SQLException e) {
System.out.println("SQL Exception catched, SQL State : " + e.getSQLState());
System.out.println("Error Code : " + e.getErrorCode());
System.out.println("Error Message : " + e.getMessage());
} catch (IOException e) {
System.out.println("Cannot parse JSON : " + jsonString);
System.out.println("Error Message : " + e.getMessage());
}
}
}
If you've noticed, I"ve corrupted the JSON to cause an IOException. Now in the json string, instead of "name", "Zname" is written which will cause Jackson Parser to fail. Let's checkout the output of this code.
Cannot parse JSON : {"Zname":"Levent","age":31,"isRegular":true}
Error Message : Unrecognized field "Zname" (class com.divilioglu.db.utils$Customer), not marked as ignorable (3 known properties: "isRegular", "name", "age"])
at [Source: (String)"{"Zname":"Levent","age":31,"isRegular":true}"; line: 1, column: 11] (through reference chain: com.divilioglu.db.utils.MySQLUtil$Customer["Zname"])
As you can see, we catched the specific scenario and we are sure, this comes from the line in dbUtil.persistCustomer() method which can be seen below;
Customer customer = objectMapper.readValue(jsonString, Customer.class);
E - Conclusion
So as it is a best practice to create new Exceptions by extending existing Exception classes. While writing your code at first, you may think that it is an overkill and you won't need additional Exception classes, but you will need them when you need distinguish the source of the problem and handle them independently.
In this example demonstrated above, I can independently catch IOException and SQLException and the sources of both Exceptions are coming from the same method. I want to distinguish both so that I can handle them independently. You cannot have that flexibility if you just wrap all the Exceptions with the base Exception class.
Exception is a standard class from which every exceptions inherit.
SQLException is a class that inherits from Exception and that is designed specifically for database(SQL) exceptions.
By doing
try {
// Your code here
} catch (Exception e) {
// Catching here
}
You are catching every type of exception possible... But then, you might not be able to know how to react to a specific exception.
but by doing
try {
// Your code here
} catch (SQLException e) {
// Catching here
}
You know that the exception happened while working on a database and it helps you know how to react to the exception.
As you see SQLException extends exception. So that's the only difference really. When you are catching exception then you will catch ALL exceptions (which is bad). But when you are catching SQLException then you catch only that(which is good because that is what you are seeking).
If an exception in between the try and catch blocks is thrown that is not a SQL Exception (these will typically only come from database-related code), for example a Null Pointer Exception, the Exception catch will catch it but the SQLException will not.
SQLException is an Exception so you are just getting a more specific exception.
According to Oracle's javadocs, this specific information you get is:
a string describing the error. This is used as the Java Exception
message, available via the method getMessage.
a "SQLstate" string, which follows either the XOPEN SQLstate
conventions or the SQL:2003 conventions. The values of the SQLState
string are described in the appropriate spec. The DatabaseMetaData
method getSQLStateType can be used to discover whether the driver
returns the XOPEN type or the SQL:2003 type.
an integer error code that is specific to each vendor. Normally this
will be the actual error code returned by the underlying database.
a chain to a next Exception. This can be used to provide additional
error information.
the causal relationship, if any for this SQLException.
SQLException is a specialized exception derived from Exception.
If you catch Exception, all exception shall get caught. Even undesirable exceptions.
If you catch only its specialiazation, the SQLException, only the SQLException itself or its derived shall get caught.
One shall catch only exceptions one can handle or wishes to handle, and let the others bubble up.
For further reference, please take a look at the following:
Exception
SQLException
SQL exception is a frequent error while working in Java Database Connectivity (JDBC).Its related to accessing or setting column in your SQL Query using prepared statement.
SQLException is a derived from Exception and contains more specific information related to accessing or setting column in your SQL query, while exception is usually more general.

Statements inside catch block doesn't execute

In the following code, I have used a wrong file name (wrongFileName.fxml) to get loaded, in order to test catch block. However, the statements inside the catch block doesn't execute. Please note, even when there is no statement to print the stack trace on the console, still stack trace gets printed. Please let me know, why this is happening?
public class First extends Application {
#Override
public void start(Stage stage){
Parent root = null;
try {
root = FXMLLoader.load(getClass().getResource("wrongFileName.fxml"));
} catch (IOException ex) {
System.out.println("SomeTextForCheck");
}
}
}
Stack trace:
Exception in Application start method
java.lang.reflect.InvocationTargetException
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.javafx.main.Main.launchApp(Main.java:698)
at com.javafx.main.Main.main(Main.java:871)
Caused by: java.lang.RuntimeException: Exception in Application start method
at com.sun.javafx.application.LauncherImpl.launchApplication1(LauncherImpl.java:403)
at com.sun.javafx.application.LauncherImpl.access$000(LauncherImpl.java:47)
at com.sun.javafx.application.LauncherImpl$1.run(LauncherImpl.java:115)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NullPointerException: Location is required.
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2773)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2757)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2743)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2730)
at javafx.fxml.FXMLLoader.load(FXMLLoader.java:2719)
at first.First.start(First.java:29)
at com.sun.javafx.application.LauncherImpl$5.run(LauncherImpl.java:319)
at com.sun.javafx.application.PlatformImpl$5.run(PlatformImpl.java:216)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:179)
at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:176)
at java.security.AccessController.doPrivileged(Native Method)
at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:176)
at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76)
at com.sun.glass.ui.gtk.GtkApplication._runLoop(Native Method)
at com.sun.glass.ui.gtk.GtkApplication$3$1.run(GtkApplication.java:89)
... 1 more
From the stack trace, RuntimeException is thrown. So Kindly handle the RuntimeException and Exception class in your code. Always log the exception or use stacktrace otherwise its difficult to debug.
public class First extends Application {
#Override
public void start(Stage stage){
Parent root = null;
try {
root = FXMLLoader.load(getClass().getResource("wrongFileName.fxml"));
} catch (IOException ex) {
System.out.println("SomeTextForCheck");
ex.printStackTrace()
}
catch(RuntimeException ex) {
System.out.println("SomeTextForCheck");
ex.printStackTrace()
}
catch(Exception ex) {
System.out.println("SomeTextForCheck");
ex.printStackTrace()
}
}
You need to catch the right exception to print the stack trace. Ideally you shouldn't be getting exceptions like NullPointerException, developers need to handle such conditions in the code.

Verify Error while invoke static function in playframework controller

I am trying to invoke a static function (Users.dashboard()) at runtime and I am getting a Verify Error exception. Users class inherits CRUD.java and does not take any params.
In Home.index():
public class Home extends Controller {
public static void index() {
for (Class<CRUD> clazz : play.Play.classloader
.getAssignableClasses(CRUD.class)) {
Dashboard d;
try {
Method m = clazz.getMethod("dashboard");
if (m != null) {
d = (Dashboard) m.invoke(clazz.newInstance(), new Object[] {});
}
} catch (SecurityException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
} catch (Exception e) {
}
}
render(dashboards);
}
Console Output:
#69iahfk3j
Internal Server Error (500) for request GET /home
Oops: VerifyError
An unexpected error occured caused by exception VerifyError: (class: controllers/Home, method: index signature: ()V) Register 1 contains wrong type
play.exceptions.UnexpectedException: Unexpected Error
at play.Invoker$Invocation.onException(Invoker.java:242)
at play.Invoker$Invocation.run(Invoker.java:284)
at Invocation.HTTP Request(Play!)
Caused by: java.lang.VerifyError: (class: controllers/Home, method: index signature: ()V) Register 1 contains wrong type
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2427)
at java.lang.Class.getDeclaredMethods(Class.java:1791)
at play.utils.Java.findActionMethod(Java.java:98)
at play.mvc.ActionInvoker.getActionMethod(ActionInvoker.java:602)
at play.mvc.ActionInvoker.resolve(ActionInvoker.java:85)
... 1 more
Public static methods in controllers are enhanced by Play so invocation on these methods can be problematic.
Did you annotation this method with #Util if it is a utility method ?
If you just wan to redirect to dashboard in this case, you can simply use redirect on the action, something like
redirect("Users.dashboard");

Why is UnknownHostException not caught in Exception (java)?

My code looks like this :
try
{
String htmlPageText=readFromHtml("http://www.yahoo.com");
}
catch (Exception e)
{
System.out.println("===Here===");
}
Method readFromHtml() will take a URL and return an HTML page. Normally it works fine. But I'm trying to simulate a "site down" situation, so I unplugged the Internet connection. I thought, the error should be caught and the result will be "===Here===", but instead, it returned:
java.net.UnknownHostException: http://www.yahoo.com"
and never printed out "===Here===". UnknownHostException is an extension of java.lang.Exception, so why was it not caught in the catch clause? Do I need a catch (UnknownHostException ex) to get it?
What is the readFromHTML method source code ? My guess is that this method throws some kind of exception but not UnknownHostException... Somewhere else in your code the exception is left unhandled.

Categories