Java - Catch Exception e - java

What does the e mean in the following code?
try {
// Do something
} catch (Exception e) {
// Do something
}
I've been researching and have gotten nothing.
System.out.println("Thanks!");

It's a variable name. Exception is the type. e is the name. You can use a different name. You might display a message to the user (or a stack trace).
try {
// Do something
} catch (Exception ohNo) {
System.out.printf("Caught exception %s doing something.%n", ohNo.toString());
ohNo.printStackTrace();
}

It is a object which contain info about an error happend.
Inherit from throwable and give you a clear message of why your code went wrong
More info
enter link description here
enter link description here

Related

How do I display database trigger errors on a web application through Payara5

This is a standard error I receive for all Errors parsed from Database Triggers. I use Payara5 as the Application Server and Netbeans 8.2 IDE. In the instance on the picture, it was supposed to display "ID Number mandatory for applicants order that 18 years of age".
How do I make sure that the exact error as in the trigger, appears on the Web Application?
Given your stacktrace it looks like you need to remove the ExceptionUtils.findRootException(ex).getMessage() and just use ex.getMessage() since the thrown topmost Exception already contains the message that you need.
I would try with the following code when an Exception is thrown:
catch (Exception ex) {
JSFUtils.addMessageSessionError(
ExceptionUtils.formatException(AdHocTools.getCurrentMethodName(),
ex.getMessage());
}
However, ExceptionUtils.findRootException(ex).getMessage() might be there for a reason. There are cases where the topmost Exception is pretty general (e.g. an EJBException) and you really need to get to the root exception to get a meaningful message.
You could also try with this code which returns an SQLException if applicable and in other cases the root Exception.
catch (Exception ex) {
Throwable rootCause = ex;
while (rootCause.getCause() != null && rootCause.getCause() != rootCause) {
if ( rootCause instanceof java.sql.SQLException ) {
break;
}
rootCause = rootCause.getCause();
}
JSFUtils.addMessageSessionError(
ExceptionUtils.formatException(AdHocTools.getCurrentMethodName(),
rootCause.getMessage());
}

Add new record to oracle database from Java Gui

I'm trying to add a new record to my oracle 11g database from javaNetbeans but it's not working. Here is my code.
private void InsertbtnActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String PositionType=jTextField1.getText().trim();
String PositionTypeDesc=jTextField2.getText().trim();
try{
Class.forName("oracle.jdbc.oracleDriver");
Connection c= DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:HRM","System","jayden");
java.sql.Statement st=c.createStatement();
st.executeUpdate("Insert into PositionType values('"+jTextField1.getText()+"','"+jTextField2.getText()+"')");
System.out.println();
JOptionPane.showMessageDialog(Null,"DATA SACVE!");
}catch (ClassNotFoundException | SQLException e){
}
}
The problem lies here:
catch (ClassNotFoundException | SQLException e){
}
Now you have a problem and
Don't know what went wrong
Don't know where it happend
Don't even known if something went wrong
When getting an exception, you should at least log it somehow, and deal with the situation properly (either rethrow it, or do error handling by showing an error dialog or something). The least you should do is:
catch (ClassNotFoundException | SQLException e){
e.printStackTrace();
}
which prints the exception (type and message) as well as the stacktrace (invocation chain, with details on which methods / code lines the exception occurred.
That will give you insights on what went wrong and what to fix.
Most probably the class name is wrong.
"oracle.jdbc.oracleDriver" is not plausible, try "oracle.jdbc.OracleDriver" where the class name begins with an upper-case O. By convention, Java class names should always begin with an upper-case letter.
But make sure to install a proper error handling as well, as suggested by the other answers / comments.

How to catch only on exception type

Is there any way to catch only based on exception types, without using an identifier, just like the way Python does. When I tried following, the compiler complains about missing identifier:
try {
doSthThatThrows();
} catch (IOException) {
handleIOException();
} catch (IllegalArgumentException) {
handleArgumentException();
}
…reporting this error:
Main.java:19: error: <identifier> expected
} catch(IllegalArgumentException)
^
1 error
In plain Java you must have an identifier for the name and you cannot use an underscore for the name (a common way to avoid giving a name/identifier in Groovy).
See the article by Oracle, Catching Multiple Exception Types and Rethrowing Exceptions with Improved Type Checking
Change your code to name a variable for the exception being thrown. For example, e in the code below. Note that you can recycle the same variable name across the catch statements.
try {
doSthThatThrows();
} catch ( IOException e ) {
…
} catch ( IllegalArgumentException e ) {
…
}

Java Error Catching Issue

I have a try/catch thing set up where it will catch all exceptions and then display the error.
Here is my code:
try {
//CODE THAT COULD ERROR HERE
} catch (final Exception e) {
System.err.println("Unexpected error: " + e.getStackTrace()[0]);
}
The above code gives me the LAST class that had the error. How do I detect the LAST class of MY PROGRAM that had the error?
Example Output: "Unexpected error: package.ClassName.method(ClassName.java:46)"
I want it to output the line of my program that had the error, not the line of a built-in java class that error-ed because of my program.
e.printStackTrace()
might make you happier. Or print the top of the array of stack trace entries available from the appropriate method.
http://docs.oracle.com/javase/6/docs/api/java/lang/Throwable.html#getStackTrace()
returns them. The first one is what you are asking for.
You can use getStackTrace to get an array of StackTraceElement instances, and filter that based on your package and/or class names (using getClassName for each element, which gives you the fully-qualified class name for that stack trace frame). That would let you winnow it down to your code rather than the JDK class the exception originated in.
try {
//error producing code
} catch (Exception e) {
for (StackTraceElement s : e.getStackTrace()) {
if (!s.getClassName().startsWith("java.")) {
System.out.println("file name: " + s.getFileName());
System.out.println("class name: " + s.getClassName());
System.out.println("method name: " + s.getMethodName());
System.out.println("line number: " + s.getLineNumber());
System.out.println();
//break; // will be the highest non java package...
}
}
}
You of course could switch it to be package specific so if (s.getClassName().startsWith("com.company")) { so it wont return for a third party library or something in the sun package or other non java package.

Print Alfresco exception

I've some problem printing the exception stack trace for Alfresco Exception.
On debug mode, step by step under Eclipse IDE I'm able to see the message when the exception is raised inspecting the Exception object but, when I send the error message to console output it's always null.
The exception is raised by this instruction:
try {
UpdateResult[] results = WebServiceFactory.getRepositoryService().update(cml);
}
catch (Exception ex) {
System.out.println(" " + ex.getStackTrace());
System.out.println("ERROR - createContent : " + ex.getMessage());
}
(in that case I tryed to write on a folder that not exists on repository) and inspecting the ex object on eclipse I can see the message:
java.lang.IllegalStateException: Failed to resolve to a single NodeRef with parameters (store=workspace:SpacesStore uuid=null path=/app:company_home/cm:UploadFromJava), found 0 nodes.
but ex.getMessage() returns null
Anyone could help me?
thanks,
Andrea
Implementing a method in this way:
NamedValue setNameProperty(String name) throws AlfrescoRuntimeException
{
try {
return Utils.createNamedValue(Constants.PROP_NAME, name);
}
catch (Exception ex) {
throw new AlfrescoRuntimeException(ex.getMessage());
}
}
The message is correclty printed with e.printStackTrace();
Try to replace your package in the log4j.properties from debug to error

Categories