I am developing a database and some JSP Pages to perform CRUD operations on it.
I cannot catch exceptions related to my SQL Code in my JSP Code.
For Example:
I have this part of code where I raise an error in T-SQL:
IF #existing > 0
BEGIN
RAISERROR ('ID primário ja existe', 1, 1)
RETURN 0
END
IF (#CategoriaId IS NULL)
BEGIN
RAISERROR('O CategoriaId não pode ser nulo',1,1)
RETURN 0
END
I need to call the function where I raise those errors in JSP code.
Heres a part of the JSP Code:
try
{
rs = stmt.executeQuery(sql);
}
catch (Exception u)
{
out.println(u.toString());
}
And it never returns the error from T-SQL.
However I know that the function reaches the catch statement because if I throw a println("test") in there it writes test on the jsp page.
I always get this exception : >com.microsoft.sqlserver.jdbc.SQLServerException: The statement did not return a result set.
This is an insert operation I'm doing, and if I write the correct values it inserts without any problems. But even when it inserts it throws that exception.
Edit: I tried u.getMessage() already
You really should read the exception message you get.
The reason you don't get the exception from the database is probably because it's masked by the exception you get from the java.
I'm a .net guy myself, the last time I've worked with java was about 17 years ago, so I'm not familiar with the correct method you should use, but it's probably not executeQuery.
According to this post, you should use execute instead.
Update
After our conversation in the comments I've done some digging and found this pearl in MSDN.
Note this part:
A RAISERROR severity of 11 to 19 executed in the TRY block of a TRY…CATCH construct causes control to transfer to the associated CATCH block. Specify a severity of 10 or lower to return messages using RAISERROR without invoking a CATCH block.
This means that your raiserror's severity parameter should be somewhere within the range of 11 to 19.
I was struggling with this with a Spring Boot project of mine. The Exception thrown would not contain the RAISERROR that exists in a MSSQL table's trigger. The ExceptionUtils.getRootCauseMessage(e) would only get the message "The transaction ended in the trigger".
Up until now I had the MSSQL Driver loaded through my projects maven pom.xml file.
The moment I placed the MSSQL Driver in my JVMs jre/lib/ext folder the RAISERROR messages where included in the Java Exception.
Related
I work on a Java application that makes fairly heavy use of Javascript to form the business logic/glue. It runs using Graal. This all works fine, but we struggle with effective error handling.
This is essentially how the JS is executed:
try {
Context context = Context.newBuilder("js").allowAllAccess(true).build()
Source s = Source.newBuilder("js", src, "script").build();
context.eval(s);
} catch (Exception e) {
LOGGER.error("Exception occurred in JavaScript:...", e);
}
So when errors happen we log them somewhere so we can do some postmortem, etc. It's possible to get the JS stack trace in these logs out of the PolyglotException that Graal throws, which is great. However, things are more complicated when some JS code has called back into Java-land, and a Java exception has been thrown:
var x = callJavaFunction("invalid parameter"); // Throws a NoSuchElementException, for example
The PolyglotException has an asHostException() method that returns the original Java-land exception, and my code that executes the JS files is smart enough to understand this and produce a useful error log. The problem arises when the JS code has tried to catch this itself, for whatever reason:
try {
var x = callJavaFunction("invalid parameter"); // NoSuchElementException
} catch (e) {
doSomeCleanup();
throw e;
}
Now we have lost the original Exception, and even worse, the JS-stack trace now just shows us the catch block, instead of where the cause was. isHostException() returns false, because this is just a JS error now. I cannot find a way to get at the original cause, which makes diagnosing errors quite difficult, especially when they have come out of a production system. The original Java exception message ends up in the JS-error object, which is helpful, but we don't have the stack trace, which is not.
What approaches can I take to try and address this?
One thought I had: Can I hook into the GraalVM and get a callback whenever a host-exception is thrown? At least that way I could have a log saying "the following Java Exceptions were thrown during execution" which I could attach to the error report. So far I've not been able to find a way to achieve this.
I am new in talend. I am trying to catch run time errors and exceptions and display meaningful message to the end user, but i am failed to do this. I saw many tutorials they use different pallets. If in one tutorial tLogCatcher is used whereas in other file it is using tAssertCatcher. I tried with both but could not do. With that i am confuse that where i have to write xpath to replace the error or exception with my own message.Can anybody help me that how to catch errors and exceptions and show meaningful messages.Thanks
You can use the tLogCatcher component to catch any errors or warnings thrown by your Talend job. To output these you can then link this to either a tLogRow component to throw them to the console (and run logs) or out to any output that Talend can connect to such as a flat file, database or even send them in an email with a tSendMail component.
If you wish to change the wording of the messages being thrown and then blindly passed on by the tLogCatcher then you could use a tMap or a tReplace or other similar component to look for your input string (the original error message) and replace it for a message of your choosing before outputting it to either the logs or some other target.
I am working on java, I read huge no.of XML files & insert them into ORACLE database but while inserting I am getting Exception, Then my program terminates without processing remaining records, Could any one please help me out from this situation, I want to read the files until unless they finished without termination of program while exception occurs.
for (File f : myFileArray) { //Or whatever you have
try {
// your code which might throw exception
} catch ( <Your exception name here> e) {
System.err.println("File failed: " + f.getAbsoultePath() );
continue; //if more code follows the try catch block, otherwise omit it
}
}
Since you did not gave any code snippet for what you actually do, I tried a guess.
As the comments suggest, you use try/catch-Blocks for handling exceptions in Java.
A good tutorial is imho
http://chortle.ccsu.edu/java5/index.html
Chapter 80 and 81.
I developed simple servlet using Apache Tomcat 6.
Firstly I write simple Hello World print servlet. Then set CLASSPATH for servlet-api.jar and compile and copy webapps/login/WEB-INF/classes/test/HelloServlet.class. That's working fine.
After I write simple JDBC connection in the servlet. I downloaded MySQL J-Connector and set CLASSPATH like this:
C:\Program Files\apache-tomcat-6.0.32\lib\servlet-api.jar;C:\Program Files\apache-tomcat-6.0.32\lib\mysql-connector-java-5.1.16-bin.jar
then try to compile; it then shows the following message:
"Unreported exception java.lang.ClassNotFoundException; must be caught or declared to be thrown"
How should I solve that?
Keep your Class.forName() under try catch block & classpath should ends with (.;) check it once.
java.lang.ClassNotFoundException is a checked exception. That means that you are required to deal with it, either by putting the call that may throw this exception inside a try { ... } catch (ClassNotFoundException e) { ... } block or by adding a throws clause to the method declaration of the method in which you make the call to the method that may throw this exception.
Read more about dealing with checked exceptions in The Catch or Specify Requirement in Oracle's Java Tutorials.
ok, im working in a j2ee project that has 2 branches in the repo and i'm ordered to mix them.
i was coding and then netbeans ask me "unreported exception blah bla bla must be caugth or declared to be thrown" and gives me the choice of just handle each exception or just throw it hoping someone else catches.
The classes i'm working with are these:
DataBase - DataObject - PersonDB(I'm working here)
DataBase an abstraction of the DBMS(supports a couple of them)
DataObject is just the CRUD, type conversion between the DBMS and java , and some reflection things for generality, it uses Database as a member variable
PersonDB is a map of the fields in the table called person to java types, this class extends DataObject
Now in the version 1(just the name actually worked in parallel) catch all the exceptions where they are produced for example in the class DataBase:
try {
Class.forName(this.driver);
} catch (ClassNotFoundException ex) {
Logger.getLogger(BD.class.getName()).log(Level.SEVERE, null, ex);
}
or in the DataObject class catching:
SQLException, NoSuchFieldException, IllegalArgumentException
now on version 2 all that is left to the up caller like this:
public BD (String Adriver, String Ahost, String Abase, String Alogin, String Apassword)
throws java.lang.ClassNotFoundException { ... }
which is the best way to go in your oppinion in this kind of issues, specially if i'm using struts
I apologize for my English
Well the first question I have to ask is: if this is a J2EE application, what are you doing manually loading JDBC drivers? This is what data sources are for.
Secondly, if you do need to dot his then ask yourself this: what is the result of this exception happening? Is it recoverable? Or is the failure so catastrophic your application can't run?
If it's so catastrophic your application can't run do this:
try {
...
} catch (SomeCheckedException e) {
throw new RuntimeException(e);
}
There is no point polluting your interfaces with "throws ..." clauses.
Alternatively if it is recoverable or potentially recoverable then you do need to handle it more nicely. It's hard to give an answer as to how though. Really it depends on the circumstances.
For example, if you're loading modules/plugins this way, you just log that plugin XYZ could not be loaded (logging the exception) and move on. If this is the direct result of a user action you need to somehow report to the user that the action failed (and also log the error), etc.
Exception handling is always a question of "Can i handle it?" - where handle means more than log and rethrow.
Sometimes it is worth to catch just to throw an exception of an other abstraction level ("Can i produce a more clear error for the caller?").
In both cases you have to think about passing the cause or not ("Has it useful informaton for the caller?") - not just do it any time, you will get tons of useless log files. When catching an exception, you would normally log the catched exception, maybe with debug level only, but in case of debugging a customers system, good log information is often the only chance to "debug" the system.
Exception handling and logging is often not done well. But for a product or longtime project it would be a good investment.