Exception - Doubt in Finally

i have doubt in finally block..
we know, the finally block statements execute whether the
exception raises in try block or not..
but in my program the print statement working after try block
without using finally block..
pls anyone expalin about this very clearly..
for example:
class excep{
     static void demo(){
          try{
               int i=1/0;
               System.out.println(i);
          }catch(ArithmeticException e){
               System.out.println(e.getMessage());
          System.out.println("Executing Finally");
     public static void main(String ar[]){
          demo();
output:
/ by zero
Executing Finally
thanks

Hi
If in your catch block you would have thrown a new exception or the same exception that you got, then the system.out.println wouldn't have been executed. Only if it would have been inside a finally block.
So:
class excep{
static void demo(){
try{
int i=1/0;
System.out.println(i);
}catch(ArithmeticException e){
throw new Exception();
System.out.println("Executing Finally");
public static void main(String ar[]){
demo();
you wouldn't get "Executing Finally" on the console.
but:
class excep{
static void demo(){
try{
int i=1/0;
System.out.println(i);
}catch(ArithmeticException e){
throw new Exception();
finally {
System.out.println("Executing Finally");
public static void main(String ar[]){
demo();
"Exceuting Finally" would be printed to the console.

Similar Messages

  • Exception doubts (urgent)

    Question no 1 :
    Given:
    boolean bool = true;
    if(bool = false) {
    System.out.println("a");
    } else if (bool) {
    System.out.println("c");
    } else if (!bool) {
    System.out.println("c");
    } else {
    System.out.println("d");
    What is the result?
    A. a
    B. b
    C. c
    D. d
    E. Compilation fails.
    Question no 2:
    class Super {
    public int i = 0;
    public Super(String text) {
    i = 1;
    public class Sub extends Super {
    public Sub(String text) {
    i = 2;
    public static void main(String args[]) {
    Sub sub = new Sub("Hello");
    System.out.println(sub.i);
    What is the result?
    A. 0
    B. 1
    C. 2
    D. Compilation fails.
    Question no 3 :
    Given:
    try {
    int x = 0;
    int y = 5 / x;
    } catch (Exception e) {
    System.out.println("Exception");
    } catch (ArithmeticException ae) {
    System.out.println("Arithmetic Exception");
    System.out.println("finished");
    What is the result?
    A. finished
    B. Exception
    C. Compilation fails.
    D. Arithmetic Exception
    Question no 4 :
    public class SyncTest{
    public static void main(String[] args) {
    final StringBuffer s1= new StringBuffer();
    final StringBuffer s2= new StringBuffer();
    new Thread () {
    public void run() {
    synchronized(s1) {
    s2.append("A");
    synchronized(s2) {
    s2.append("B");
    System.out.print(s1);
    System.out.print(s2);
    }.start();
    new Thread() {
    public void run() {
    synchronized(s2) {
    s2.append("C");
    synchronized(s1) {
    s1.append("D");
    System.out.print(s2);
    System.out.print(s1);
    }.start();
    Which two statements are true? (Choose Two)
    A. The program prints "ABBCAD"
    B. The program prints "CDDACB"
    C. The program prints "ADCBADBC"
    D. The output is a non-deterministic point because of a possible deadlock condition.
    E. The output is dependent on the threading model of the system the program is
    running on.

    Bloody cross-poster
    http://forum.java.sun.com/thread.jspa?threadID=639843
    Do your homework yourself.

  • Return in finally block hides exception in catch block

    Hi,
    if the line marked with "!!!" is commented out, the re-thrown exception is not seen by the caller (because of the return in the finally block). If the line is commented in, it works as I would expect. Is this is bug or a feature? I assume the return removes the call to troubleMaker() from the call stack - including the associated exception...
    Christian Treber
    [email protected]
    public class ExceptionDemo extends TestCase
    public void testException()
    String lResult = "[not set]";
    try
    lResult = troubleMaker();
    System.out.println("No exception from troubleMaker()");
    } catch(Exception e)
    System.out.println("Caught an exception from troubleMaker(): " + e);
    System.out.println("Result: " + lResult);
    public String troubleMaker()
    boolean lErrorP = false;
    try
    if(6 > 5)
    throw new RuntimeException("Initial exception");
    return "normal";
    } catch (RuntimeException e)
    System.out.println("Caught runtime exception " + e);
    lErrorP = true;
    throw new RuntimeException("Exception within catch");
    } finally
    System.out.println("Finally! Error: " + lErrorP);
    if(!lErrorP)
    return "finally";

    This is specified in the Java Language Specification, section 14.19.2 .
    -- quote
    If execution of the try block completes abruptly because of a throw of a value V, then there is a choice:
    * If the run-time type of V is assignable to the parameter of any catch clause of the try statement, then the first (leftmost) such catch clause is selected. The value V is assigned to the parameter of the selected catch clause, and the Block of that catch clause is executed. Then there is a choice:
    o If the catch block completes normally, then the finally block is executed. Then there is a choice:
    + If the finally block completes abruptly for any reason, then the try statement completes abruptly for the same reason.
    -- end quote
    "completing abruptly" (in this instance) means a throw or a return, as specified in section 14.1
    Ok? It's not a bug, it's the defined behaviour of the language. And when you think about it, this behaviour gives you the option to do what you want in your finally block.

  • Exception in finally

    hi,
    i throw an Exception in try block and also throw an Exception in finally block. why do i get only the Exception thrown in finally block.
    i completely lose the Exception thrown in try block.
    The reason i'm asking this is because of the way JUnit is written.
    They call Setup and tests in try block and tearDown in a finally block.
    if an Exception happens in test and also Exception happens in tearDown, the test results show the test failed with exception in tearDown. Actually i expect the results to show as test failed in the test. Is this a java bug?
    thanks
    venkat

    If I did understand your question right, I find it very strange. For my it works as expected.
    Sounds very strange, you should get the thrown Exception in both the try-catch and in your finally-try-catch.
    try to just fill your stack and see if it will be displayd later in the finallys thrown exception. (use the fillinstacktrace).
        public void doSomething()
            int[] a = new int[2];
            String b = null;
            try
                System.out.println( a[3] );
            catch( ArrayIndexOutOfBoundsException aioobe )
                System.out.println("in catch");
                sleep(500);
                aioobe.printStackTrace();
                throw (ArrayIndexOutOfBoundsException) aioobe.fillInStackTrace();
            finally
                try
                    System.out.println( b.length() );
                catch( NullPointerException npe )
                    System.out.println("in finally");
                    sleep(500);
                    npe.printStackTrace();
        }good luck!

  • Exception: Given final block not properly padded

    Hi,
    I generated an password encrypted RSA private key using the following openssl command.
    openssl pkcs8 -topk8 -in private.pem -outform DER -out private.der -v2 des3
    I am using the following piece of code to decrypt private.der using a password entered by the user.
    For now, I assume that the password is of 24 bytes long.
    1. The following method throws an exception saying "Given final block not properly padded."
    How can I fix it?
    2. Since private.der is created by openssl, I didn't provide salt and iv paramters.
    Are they embedded in the file itself?
    Does the objects in the following method takes care of them automatically?
    Thanks.
    public byte[] readDES3EncryptedPrivateKey2(final String password,
                                                final String privateKeyFilePath)
    throws Exception
            File privateKeyFile = new File(privateKeyFilePath);
            byte[] encryptedPrivateKey = FileUtils.readFileToByteArray(privateKeyFile);
            final byte[] passwordInBytes = password.getBytes("UTF-8");
            DESedeKeySpec keySpec = new DESedeKeySpec(passwordInBytes);
            SecretKey key = SecretKeyFactory.getInstance(DES3).generateSecret(keySpec);
            javax.crypto.EncryptedPrivateKeyInfo epki = new javax.crypto.EncryptedPrivateKeyInfo(
                    encryptedPrivateKey);
            AlgorithmParameters ap = epki.getAlgParameters();
            des3Cipher.init(Cipher.DECRYPT_MODE, key, ap);
            // Error: Given final block not properly padded
            return des3Cipher.doFinal(epki.getEncryptedData());
        }

    I've run into similar things. Have you tried padding the data you are trying decrypt to the block size of DES3?

  • Finally cause Exception be forgotten

    In trying out that finally cause previous return value be forgotten, as described on page 206 of "The Java Programming Language, 3rd edition", I wrote the following code, and tested it with jdk1.3.1. To my supprise, not only the return value was forgotten, the exception was appeared forgotten as well:
    class PException extends Exception {
    class Final {
        void f1(int i) {
         int result;
         System.out.println("f1("+i+")");
         try {
             result = f2(i);
             System.out.println("result = " + result);
         } catch(Exception e) {
             System.out.println("caught an Exception: " + e);
         try {
             result = f3(i);
             System.out.println("result = " + result);
         } catch(Exception e) {
             System.out.println("caught an Exception: " + e);
        int f2(int i) throws PException {
         try {
             if (i == 1) {
              System.out.println("generate exception");
              throw new PException();
             return 1;
         } finally {
             return 2;
        int f3(int i) throws PException {
         if (i == 1) {
             System.out.println("generate exception");
             throw new PException();
         return 1;
        public static void main(String[] args) {
         Final f = new Final();
         f.f1(1);
         f.f1(2);
         f.f1(1);
    }Here is the result:
    f1(1)
    generate exception
    result = 2
    generate exception
    caught an Exception: PException
    f1(2)
    result = 2
    result = 1
    f1(1)
    generate exception
    result = 2
    generate exception
    caught an Exception: PException

    The concern here is that when the
    try {
    finally {
    }pattern is used, without the catch block, purelly for flow control purpose, a return statement in the finally block could be problematic. If a finally block ends with a return statement, any exception that might be thrown in the try block would be ignored. The unhandled exception will not propergate, it simply lost in the midst. Because any code could throw unchecked exception, if the exception cannot afford to be lost, then one should be careful not to use return in the finally block. See the following test code:
    class Finally {
        void test() {
         int result;
         System.out.println("test()");
         try {
             result = f1();
             System.out.println("result = " + result);
         } catch(Exception e) {
             System.out.println("Caught an Exception: " + e);
         try {
             result = f2();
             System.out.println("result = " + result);
         } catch(Exception e) {
             System.out.println("Caught an Exception: " + e);
         try {
             f3();
         } catch(Exception e) {
             System.out.println("Caught an Exception: " + e);
         try {
             f4();
         } catch(Exception e) {
             System.out.println("Caught an Exception: " + e);
        int f1() {
         System.out.println("f1()");
         int a = 0;
         int b = 0;
         try {
             a = 1/0;  // this generate an unchecked exception
             b = 1;
         } finally {
             return b; // this return clobber the unchecked exception
        int f2() {
         System.out.println("f2()");
         int a = 0;
         int b = 0;
         a = 1/0; // this generate an unchecked exception
         b = 1;
         return b;
        void f3() {
         System.out.println("f3()");
         int a = 0;
         int b = 0;
         try {
             a = 1/0;  // this generate an unchecked exception
             b = 1;
         } finally {
             return;   // this return clobber the unchecked exception
        void f4() {
         System.out.println("f4()");
         int a = 0;
         int b = 0;
         try {
             a = 1/0;  // this generate an unchecked exception
             b = 1;
         } finally {
        public static void main(String[] args) {
         Finally f = new Finally();
         f.test();
    /code]
    Here are the results:test()
    f1()
    result = 0
    f2()
    Caught an Exception: java.lang.ArithmeticException: / by zero
    f3()
    f4()
    Caught an Exception: java.lang.ArithmeticException: / by zero
    We see that the devide by zero exception throw by f1() simply vanished, the unintended result 0, instead of the intended result 1, is returned. The test() method did not detect any abnormality in f1(), which is scary. To drive the point home, we try f3() and f4(), which has void return type. A simple return statement in f3() causes exception be lost. The stack frame seems intact, for otherwise, the test() method would exit abruptly before f2() even get a chance to be called.

  • Ignored exception in try with finally

    Hello,
    I do not understand why the following code (more precisely the line marked with //**) compiles well. It seems to break the catch or throws rule of the Java exceptions. Method3 throws Exception, but it is not necessary either to surround method3 call in a try-catch block or to add a throws Exception clause in method1.
    Can anybody explain me why this code compiles well?
    public class TestCase {
      public static void main(String[] args) {
        method1();
      private static boolean method1() {
        try {
          method2();
        } catch (Exception e) {
          method3(); // **
        } finally {
          // If I place here the return
          // code compiles perfectly, even without
          // surrounding the ** line with a try-catch
          return true;
        // But if the return is placed here, code does not compile
    //    return true;
      private static void method2() throws Exception {
        System.out.println("Method2");
        throw new Exception();
      private static void method3() throws Exception {
        System.out.println("Method3");
        throw new Exception();
    }Thank you in advance.

    As you observe, if you take the "return true" out of the finally block and put it at the end of the method the code will not compile. In this case method2() might throw an Exception sending you into the catch bit. Then method3() might throw an Exception. At this point the try statement as a whole - the try, catch and now empty finally parts - will have thrown an Exception and the compiler demands you declare this with throws.
    Now the code you posted is deceptively similar, but quite different in effect. Again method2() might result in an Exception and so might method3(). But neither of these facts counts for much: the finally block will always be executed and it will always return true. Game over! So method1() always returns true and never anything else and, in particular, never throws an Exception. The compiler knows this and compiles your code.
    It is true that exceptions must be caught or thrown. The point is that the try statement as a whole does not (and cannot) throw an exception, so the rule never comes into play.
    Much the same happens if your finally bit throws some other exception. The exception (or return) within the finally part is garanteed to occur and will take precedence over any other exception or return that occurs before.
    [Edit] block->statement in line with the following post

  • Catching causal exceptions from finally{} block?

    I have some code that I have not developed, yet from what I can tell throws Exceptions as in the following psuedo-code:
    public void foobar() throws BarException, FooException {
            try {
                  throw new FooException();
            } finally {
                    throw new BarException();
    }This expectedly returns BarException, not FooException. Question is since FooException was thrown, is there any way to get a reference to the original cause?

    This is due to the good-ol' problem of cleaning up
    java.sql.Connection objects to a connection pool in
    the finally block yet wanting to ensure the original
    exception is propagated to the calling method,
    whereas the OP should catch the exception,
    maintain temporary reference, then use it as a
    reference to the other Exception in the finally
    if there's no better way for her to do it.There's a better way to do it. You don't need to keep a temp reference to that exception in your finally block. Finally doesn't need to know anything about the exception. public void foo() {
        try {
            Bar bar = sqlStuff();
        catch (SQLException exc) {
            // This catch block will execute if  SQLException is thrown at *1*
            System.err.println("I got a SQLException!");
    private Bar sqlStuff() throws SQLException, MyException {
        try {
            // *1* do something that might throws SQLException, and maybe something else
            return aBar;
        catch (SomeOtherException exc) {
            throw new MyException(exc);
        finally {
            // close ResultSet, Statement, Connection
            // NO EXCEPTION re-throwing
        // or return aBar here
    } If a SQLException is thrown inside the try block, finally will execute, and then the method will throw that original SQL exception. If SomeOtherException is thrown, it will be caught, a new MyException will be created to wrap it, the finally block will execute, and the MyException will be thrown from the method. If everything goes well, the finally block will execute, and the method will return aBar.
    All this will happen without the finally block touching or knowing about any exception that was thrown before entering it.

  • Mac Pro for Final Cut Studio -- The Buying Guide

    I am starting to think about upgrading my "old" Power Mac G5 Quad system to a Mac Pro system. As you might expect, this raises several issues.
    What I do: I edit DV and HDV on FCS2. My specs are below. I am looking for the best speed (especially for rendering), stability and video quality I can afford (between $5,000 and $6,000).
    Question 1: Is it true that Snow Leopard and FCP 7 are about a year away? If so, please assume for the following questions that I would be working with the full complement of FCS2 applications on the Leopard OS. (How worth waiting for do you think these are?)
    Question 2: Without directing me to the various benchmark and testing sites (which I’ve already looked at), can you suggest the actual performance differences I would see (again, using the whole range of FCS2 apps) in the following:
    Two 2.26GHz Quad-Core Intel Xeon processors
    Two 2.66GHz Quad-Core Intel Xeon processors
    Question 3: I have heard that (with the exception of Compressor) FCS can only use a maximum of 4GB of RAM, and that the 6GB that the Mac Pro ships with are already more than it can use. Is this true? Is it true that Snow Leopard would allow FCS to make greater use of more RAM? And would this show up in the programs’ performance?
    Question 4: To get the best video performance with my various FCS2 applications, is there a significant quality improvement in moving up from the NVIDIA GeForce GT 120 512MB to one of the other video cards? How would I notice a difference in the quality?
    Question 5: Are there any other purchasing considerations I should think about when configuring a new Mac Pro?
    Thanks a lot.
    Giraut

    Well, well, well, you make me think more about my last upgrade of an ATI Radeon 2600 to the latest ATI Radeon HD 4870!
    I was looking on the Final Cut Pro thread to find one answer and look what I found, your questions!
    Since yesterday night I was seeking the Apple Support threads just for fun and I now have doubts.
    I am a Mac Pro (earlier 2008) owner. I upgraded it to 4 x 1.5 Tb Seagate hard drives and 10G of RAM from OWC (Other Word Computing). First let me tell you NOT to buy from Apple Store for your hard drive and/or memory upgrade. They are totally out of price list. I got my Mac Pro first with one 500 Gb Seagate drive. Then I added 2 x 500 Gb hard drives from Apple. I payed them 199,00 $ each
    Last September, I upgraded the drive bays with 4 x 1.5 Tb from OWC. I paid them 229.00 $ each!
    199,00 $ for 500 Gb or 229,00 $ for 1.5 Tb (that"s 3 times 500 Gb) which one would you take? And we are talking about two models from Seagate running at 7200 RPM, with 32 Mb of buffer.
    I mean... What is that?!!?
    And the memory! Don't even think about it.
    I got first 4GB Matched Set (2 x 2GB) for 147,99 $ in September from OWC and my second order was 4GB Matched Set (2 x 2GB) for 132,79 $ in October.
    I payed a total of 280,78 $ for 8GB of RAM while the price for this upgrade on Apple Store woul have cost me 1998,00 $
    *+Source Apple Store :+*
    *+Apple Memory Module 4GB 800MHz DDR2 FB-DIMM ECC 2x2GB $999.00+*
    Multiply that by 2!
    Now how much memory would you need?
    I am not a Final Cut Pro user, but I use Final Cut Express a lot, with animation QuickTime movies exported from my Astronomy software Starry Night Pro Plus.
    Yesterday I posted this into a thread to answer a user :
    +Every morning I have my preferred applications started: Mail, Safari, iTune, Aperture and Final Cut Express. I just did a test for you. I started Mail, Safari, Aperture, Final Cut Express, Starry Night Pro Plus (OpenGL Astronomy Software), Terminal, Quicktime, TextEdit and NeoOffice.+
    +With all these apps running, I still have 6.48G of Free RAM out from the 10G installed!+
    +It's when I start hungry applications like VMWare Fusion running Windows XP, or Quicktime with a lot of movies opened that I could see the memory level going low!+
    +Your bottle neck in video editing will probably be the video card, after the disk speed. Be sure to use 7200 RPM disk and eSATA for your video plans if possible. Firewire 800 will works fine on external drive but it could giggle. I had an ATI Radeon HD 2600 that I recently upgraded to an ATI Radeon HD 4870. the drivers aren't ready yet from Apple. We are all waiting for the next OS X release 10.5.7 for the drivers! For now, I am running on Beta drivers.+
    +It's hard to say by now if I have better performance into Final Cut Express because the movie I was working on was an animation movie using plans exported from Starry Night Pro Plus via Quicktime and "animation" codec without any compression. As soon as I make a modification, I still have to render the output for smooth playing.+
    Now, after some test with Starry Night Pro Plus this morning, I can safety say that Starry Night Pro Plus with Open GL does use my video card extra speed and that my experience navigating into the Universe is much better and smooth.
    But honestly, even if I have to admit that I am using the Beta drivers for the HD 4870, I must say that I have very big doubt that Final Cut Express does use the extra power of the HD 4870 compare to the HD 2600!
    In fact, I am searching the support thread for this answer.
    Does anyone can say if Final Cut Express or Final Cut Pro does make use of the extra hardware feature of the ATI Radeon HD 4870 or not?

  • How to catch Exception in a JSP

    Hi there,
    I'm building my first JSP application. I still don't know what happens to an exception thrown inside a scrptlet in a JSP page.
    My JSP page is resultados.jsp (it processes a DB query):
    <%@ page contentType="text/html; charset=iso-8859-1" language="java"
    import="java.lang.*,java.sql.*,pcliente.*" errorPage="error.jsp" session="true" %>
    <html>
    <head>
    <title>PCliente - Hist?rico de Mainframe</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    <body background="imagens/sm_bg.gif">
    <TABLE border=0 cellPadding=0 cellSpacing=0>
    <TR>
    <TD width=5><IMG alt="" height=1 src="imagens/pixel.gif" width=5></TD>
    <TD vAlign=top width=125><jsp:include page="menu.jsp" flush="true" /> </TD>
    <TD width=25><IMG alt="" height=1 src="imagens/pixel.gif" width=25></TD>
    <TD vAlign=top width=365>
    <%
    try
    PCliente pcliente = new PCliente(request.getParameter("maquina"),
                        request.getParameter("acessorio"),
                        request.getParameter("contrato"),
                        request.getParameter("estabelecimento"),
                        request.getParameter("ifiscal"));
    ResultSet rs = pcliente.executarQuery();
    while (rs.next())
    out.println("<BR>" + rs.getString("nome_estab_instalacao"));
    out.print(" -----" + rs.getString("num_serie_equipamento"));
    out.print(" -----" + rs.getString("num_contrato"));
    /*** SQL exception is thrown by pcliente.executarQuery() ***/
    catch (SQLException sqlEx)
    out.println("<P>" + "There was an error doing the query:");
    out.println ("<PRE>" + sqlEx + "</PRE> \n <P>");
    application.log("Exception lan?ada", sqlEx);
    throw new Exception(sqlEx.toString());
    finally
    out.println("<P>" + "FINALLY !!!");
    %>
    </TD>
    </TR>
    </TABLE>
    </body>
    </html>
    The error.jsp is
    <%@ page contentType="text/html; charset=iso-8859-1" language="java" import="java.sql.*,pcliente.*" isErrorPage="true" session="true" %>
    <html>
    <head>
    <title>PCliente - Hist?rico de Mainframe - Erro</title>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
    </head>
    <body>
    <strong>Pagina de Erro</strong>
    </body>
    </html>
    The java class I'm using in this JSP is pcliente/PCliente with the source code:
    package pcliente;
    import java.sql.*;
    public class PCliente
    private String numSerieMaquina, numSerieAcessorio, numContrato, numEstabelecimento, ifiscal;
    private String strQuery;
    private Connection conn;
    private ResultSet rs;
    private Statement stmt;
    public PCliente(String numSerieMaquina, String numSerieAcessorio,
                        String numContrato, String numEstabelecimento,
                        String ifiscal)
    conn = null;
    rs = null;
    stmt = null;
    this.numSerieMaquina = numSerieMaquina;
    this.numSerieAcessorio = numSerieAcessorio;
    this.numContrato = numContrato;
    this.numEstabelecimento = numEstabelecimento;
    this.ifiscal = ifiscal;
    construirQuery();
    public ResultSet executarQuery() throws SQLException
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
    /* This causes SQLException as a 'c' was taken from oracle in
    "jdbc:orale:oci8:@PROD" */
    conn = DriverManager.getConnection("jdbc:orale:oci8:@PROD","histmain", "histmain");
    stmt = conn.createStatement();
    rs = stmt.executeQuery(strQuery);
    return rs;
    private void construirQuery()
    strQuery = "SELECT num_serie_equipamento, num_contrato,
    nome_estab_instalacao" +
         " FROM anmpf04" +
         " WHERE 1 = 1";
    if (numSerieMaquina != null)
    if (numSerieMaquina.indexOf('%') == -1)
    strQuery += " AND num_serie_facturacao = " + numSerieMaquina;
    else     
    strQuery += " AND num_serie_facturacao LIKE '" + numSerieMaquina + "'";
    When I execute the JSP I see a page with the text FINALLY !!!
    But an exception was thrown and I can't,
    see
    out.println("<P>" + "There was an error doing the query:");
    out.println ("<PRE>" + sqlEx + "</PRE> \n <P>");
    in the jsp page
    application.log("Exception lan?ada", sqlEx);
    don't know where to find the log file
    throw new Exception(sqlEx.toString());
    isn't caught by the error page error.jsp
    What am I missing here ? a lot of stuff no doubt !
    Can anyone give me suggestion(s) on how to detect an Exception ?
    I would also apreciate a site with documentation regarding Exception processing inside JSP.
    Many thanks,
    MGoncalv

    Hi there,
    I'm building my first JSP application. I still don't
    know what happens to an exception thrown inside a
    scrptlet in a JSP page.I believe that any scriptlet exceptions get wrapped into a ServletException. At that time, if you have an errorPage defined for you JSP page, then it will go there. If you don't then the server will try to find the particular exception type in an <error-page> stanza in the web.xml. If it finds a mapping, it will go to that mapping, otherwise it will go to a default error page (container specific).
    A quick glance at your design shows some big problems though that you may or may not hit (depending on how often you hit the page in your testing). The primary one is that in your PCliente class, you are opening up database connections/statements/results sets w/o closing them. You will run out of connections/cursors at some point b/c of this. You need to do your reads from the database and then close those resources (in a finally block to make sure they get closed). Read the data in a lightweight java object that the JSP can use to actually get the data.
    Also, you only need to register the driver manager once. You can do this in static initialization block.
    ncuka

  • Return statement in exception and consequences

    Hi,
    Can any one give me the explanation for my doubt?
    Case 1:
    I am having some code throwing some exception lets say arithematic exception in my try block.
    I caught it in the catch block and at last I am having one finally?
    as per normal order try block next catch block and at last finally will execute.
    I execute the above code by putting a return statement inside catch block.I got the same order of execution irrespective of return statement inside catch?
    What is the significance of return inside catch?
    Case 2:
    Lets take the scenario.
    class MyException
         public static void main(String[] args)
              int i=1,j=0;
              try
                   try
                   System.out.println("the value is: "+(i/j));
                   System.out.println("Inside try block");
                   catch(ArithmeticException e)
                   System.out.println("hi in ame");
                   //return;
              finally
              System.out.println("inner finally");
                                            System.out.println("outer try");
              catch(Exception e)
                             e.printStackTrace();
                   System.out.println("in exception");
              finally
                   System.out.println("plz wait");
    If return statement is there inside the inner try and catch the code out of inside outer try not getting executed Why So?
    Any clarifications?
    Thanking you,
    Murthy.

    First, please format your code as per http://forum.java.sun.com/features.jsp#Formatting
    I'm not sure what part you don't understand.
    .    public static void main(String[] args) {
    .        try {
    .            try {
    .                throw new ArithmeticException();
    .                System.out.println("Inside try block"); // #1
    .            catch(ArithmeticException e) {
    .                System.out.println("hi in ame"); // #2
    .                return;
    .            finally {
    .                System.out.println("inner finally"); // #3
    .            System.out.println("outer try"); // #4
    .        catch(Exception e) {
    .            System.out.println("in exception"); // #5
    .        finally {
    .            System.out.println("plz wait"); // #6
    .    }#1 -- You won't get here because you throw AME.
    #2 -- You will get here because you caught the AME you just threw.
    #3 -- You will get here because it's a finally
    #4 -- You won't get here. I think that this is what you're asking about: Why don't we get here? Because we've already done 'return' and this line is NOT inside a finally. The only things that can get executed after a return are finally blocks.
    #5 -- You won't get here because you already caught the AME and didn't rethrow it or any other exception.
    #6 -- You will get here because it's a finally.
    Once you do a return, the only code you can execute before exiting the method are finally blocks. First the one corresponding to the try/cathc block where your return is, then the finally for the try/catch that encloses that one, and so on outward. The code between one finally and the next (#4 here) is NOT executed.
    If you still have a question, please try to clarify exactly what behavior you don't understand.
    Don't return from inside t/c/f.

  • Doubt in program

    hi to all
    help me plz
    i am doing program in java
    description of my program
    1. i created start date and end date, it has to compare, then the dates has to go to the database,
    2. in databse i created a table called holidays(in holiday table there is a list of public holidays and weekend )
    3. the start date and end date has to go there and check these dates are in public holidays are in weekends
    if yes means it has tel reaining days are weekdays
    here is my doubt
    i created to compare and i connected to my database , but i dount know the query to send the dates
    plz help me
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Date;
    import java.text.*;
    import java.sql.*;
    public class compareDates
         public static boolean compareDates(String dDateA, String dDateB)
         Connection con = null;
                  Statement stmt = null;
                  ResultSet rs = null;
         try
                  String driverName = "com.mysql.jdbc.Driver";
                  Class.forName(driverName);
         String serverName = "192.168.10.5";
         String mydatabase = "Trainees";
         String url = "jdbc:mysql://" + serverName +  "/" + mydatabase; // a JDBC url
         String username = "josep";
         String password = "josep";
         con = DriverManager.getConnection(url, username, password);
         stmt=con.createStatement();
                 System.out.println("Entered into Compare Dates");
                 SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
                 ParsePosition pos = new ParsePosition(0);
                 ParsePosition pos1 = new ParsePosition(0);
                 Date startDate = formatter.parse(dDateA, pos);
                 Date endDate = formatter.parse(dDateB, pos1);
                 boolean flag = false;
                 System.out.println("Start Date :"+startDate);
                 System.out.println("End Date   :"+endDate);
                 if(startDate.before(endDate))
                 flag = true;
                 System.out.println("Compare Flag :"+flag);
                 return flag;
                 stmt.executeUpdate("insert into Holiday(HolidayDate) values (' "+dDateA+"',' "+date2+"')");
                  System.out.println("data inserted");
             catch(Exception e)
             System.err.println("Exception: " + e.getMessage());
             finally
                 try
                 if(con != null)
                 con.close();
               catch(SQLException e)
    return false;
        public static void main(String args[])throws IOException
           try
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.println ("Enter Start Date (dd/mm/yyyy)");
            String dDateA=br.readLine();
            System.out.println("Enter End Date (dd/mm/yyyy)");
            String dDateB= br.readLine();
            compareDates cd= new compareDates();
            boolean before = cd.compareDates(dDateA,dDateB);;
            if(!before)
             System.out.println("Please enter the Correct Date ");
           catch(Exception e)
                  System.out.println("Exception in main Class :"+e.getMessage());
    }plz send ur suggestions

    helo sir,
    thk u for ur reply
    but i am getting error in this line
    stmt.executeUpdate("insert into Holiday values('"+getStrDATETIMEFromDate(dDateA)+"','"+getStrDATETIMEFromDate(date2)+"')");
    in the program i used ur code like this
    import java.io.BufferedReader;
    import java.io.IOException;
    import java.io.InputStreamReader;
    import java.util.Date;
    import java.text.*;
    import java.sql.*;
    public class compareDates
          private static SimpleDateFormat mDateTimeFormater = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
         public static String getStrDATETIMEFromDate(Date pDate)
              String lsResult = "";
              synchronized (mDateTimeFormater)
                   lsResult = mDateTimeFormater.format(pDate);
              return lsResult;
         public static boolean compareDates(String dDateA, String dDateB)
         Connection con = null;
                  Statement stmt = null;
                  ResultSet rs = null;
         try
                  String driverName = "com.mysql.jdbc.Driver";
                  Class.forName(driverName);
         String serverName = "192.168.10.5";
         String mydatabase = "Trainees";
         String url = "jdbc:mysql://" + serverName +  "/" + mydatabase; // a JDBC url
         String username = "josep";
         String password = "josep";
         con = DriverManager.getConnection(url, username, password);
         stmt=con.createStatement();
                 System.out.println("Entered into Compare Dates");
                 SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
                 ParsePosition pos = new ParsePosition(0);
                 ParsePosition pos1 = new ParsePosition(0);
                 Date startDate = formatter.parse(dDateA, pos);
                 Date endDate = formatter.parse(dDateB, pos1);
                 boolean flag = false;
                 System.out.println("Start Date :"+startDate);
                 System.out.println("End Date   :"+endDate);
                 if(startDate.before(endDate))
                 flag = true;
                 System.out.println("Compare Flag :"+flag);
                // return flag;
    stmt.executeUpdate("insert into Holiday values('"+getStrDATETIMEFromDate(dDateA)+"','"+getStrDATETIMEFromDate(dDateB)+"')");
                  System.out.println("data inserted");
             catch(Exception e)
             System.err.println("Exception: " + e.getMessage());
             finally
                 try
                 if(con != null)
                 con.close();
               catch(SQLException e)
    return false;
        public static void main(String args[])throws IOException
           try
            BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
            System.out.println ("Enter Start Date (dd/mm/yyyy)");
            String dDateA=br.readLine();
            System.out.println("Enter End Date (dd/mm/yyyy)");
            String dDateB= br.readLine();
            compareDates cd= new compareDates();
            boolean before = cd.compareDates(dDateA,dDateB);;
            if(!before)
             System.out.println("Please enter the Correct Date ");
           catch(Exception e)
                  System.out.println("Exception in main Class :"+e.getMessage());
    }but i am getting error as
    javac compareDates.javacompareDates.java:57: getStrDATETIMEFromDate(java.util.Date) in compareDates can
    not be applied to (java.lang.String)
    stmt.executeUpdate("insert into Holiday values('"+getStrDATETIMEFromDate(dDateA)
    +"','"+getStrDATETIMEFromDate(dDateB)+"')");
    ^
    compareDates.java:57: getStrDATETIMEFromDate(java.util.Date) in compareDates can
    not be applied to (java.lang.String)
    stmt.executeUpdate("insert into Holiday values('"+getStrDATETIMEFromDate(dDateA)
    +"','"+getStrDATETIMEFromDate(dDateB)+"')");
    ^
    2 errors
    plz sir help me to insert in database

  • Problem with final variables and inner classes

    variables accessed by inner classes need to be final. Else it gives compilation error. Such clases work finw from prompt. But when I try to run such classes through webstart it gives me error/exception for those final variables being accessed from inner class.
    Is there any solution to this?
    Exception is:
    java.lang.ClassFormatError: com/icorbroker/fx/client/screens/batchorder/BatchOrderFrame$2 (Illegal Variable name " val$l_table")
         at java.lang.ClassLoader.defineClass0(Native Method)
         at java.lang.ClassLoader.defineClass(ClassLoader.java:502)
         at java.security.SecureClassLoader.defineClass(SecureClassLoader.java:123)
         at com.sun.jnlp.JNLPClassLoader.defineClass(Unknown Source)
         at com.sun.jnlp.JNLPClassLoader.access$1(Unknown Source)
         at com.sun.jnlp.JNLPClassLoader$1.run(Unknown Source)
         at java.security.AccessController.doPrivileged(Native Method)
         at com.sun.jnlp.JNLPClassLoader.findClass(Unknown Source)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:299)
         at java.lang.ClassLoader.loadClass(ClassLoader.java:255)
         at java.lang.ClassLoader.loadClassInternal(ClassLoader.java:315)
         at com.icorbroker.fx.client.screens.batchorder.BatchOrderFrame.<init>(BatchOrderFrame.java:217)
         at com.icorbroker.fx.client.screens.batchorder.BatchOrderViewController.createView(BatchOrderViewController.java:150)
         at com.icorbroker.fx.client.screens.RealTimeViewController.initialize(RealTimeViewController.java:23)
         at com.icorbroker.fx.client.screens.batchorder.BatchOrderViewController.<init>(BatchOrderViewController.java:62)
         at com.icorbroker.fx.client.screens.displayelements.DisplayPanel$3.mousePressed(DisplayPanel.java:267)
         at java.awt.Component.processMouseEvent(Component.java:5131)
         at java.awt.Component.processEvent(Component.java:4931)
         at java.awt.Container.processEvent(Container.java:1566)
         at java.awt.Component.dispatchEventImpl(Component.java:3639)
         at java.awt.Container.dispatchEventImpl(Container.java:1623)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.LightweightDispatcher.retargetMouseEvent(Container.java:3450)
         at java.awt.LightweightDispatcher.processMouseEvent(Container.java:3162)
         at java.awt.LightweightDispatcher.dispatchEvent(Container.java:3095)
         at java.awt.Container.dispatchEventImpl(Container.java:1609)
         at java.awt.Window.dispatchEventImpl(Window.java:1590)
         at java.awt.Component.dispatchEvent(Component.java:3480)
         at java.awt.EventQueue.dispatchEvent(EventQueue.java:450)
         at java.awt.EventDispatchThread.pumpOneEventForHierarchy(EventDispatchThread.java:197)
         at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:150)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:144)
         at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:136)
         at java.awt.EventDispatchThread.run(EventDispatchThread.java:99)

    I've also been having the same problem. The only work-around seems to be to slightly change the code, recompile & hope it works. See http://forum.java.sun.com/thread.jsp?forum=38&thread=372291

  • Exception while excel processing after upload using commons file upload

    Hi all,
    I am experiencing problem while creating a workbook after getting the input stream from the uploaded file. its not going catch block instead it is going to finally and giving null pointer exeption in finally as one variable in finally is not defined. the variable is defined in try as well as catch but during run time the variable is not getting assigned any value also. I'll put the code over here. please help me with a solution
    import org.w3c.dom.* ;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import jxl.*;
    import org.apache.commons.fileupload.*;
    import org.apache.commons.fileupload.disk.*;
    import org.apache.commons.fileupload.servlet.*;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    public class CescoreUploadServlet extends baseHttpServlet
         private DataSource cesDS = null;
         public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
              doPost(req, res);
         public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
              String targetPage = null;
              File f = null;
              System.out.println("Upload Controller");
              HttpSession session = req.getSession(true);
              try
                   if(cesDS == null){
                        cesDS = new JNDIDataSource(getServletContext().getInitParameter(Constants.DATA_SOURCE_NAME));
                   CesRepository cRep = new CesRepository(cesDS);
                   if (session.getAttribute("DataContainerInfo") == null) {
                        System.out.println("Initializing DataContainerInfo");
                        DataContainer DataContainer = new DataContainer();
                        cRep.setInitialParameters(DataContainer);
                        session.setAttribute("DataContainerInfo",DataContainer);
                   else System.out.println("DataContainerInfo is available");
                   UserInfo userInfo = null;               
                   String login_id = req.getRemoteUser();
                   if(session.getAttribute("UserID") != null) login_id = (String)session.getAttribute("UserID");
                   if(session.getAttribute("userProfile") == null ) session.setAttribute("userProfile", cRep.getUserInfo(login_id));
                   userInfo = (UserInfo)session.getAttribute("userProfile");
                   System.out.println("<<<<<< userInfo contains : "+userInfo.getHrID()+" >>>>>>");
                   String projIdValue = null;
                   String msg = null;
                   boolean isMultipart = FileUpload.isMultipartContent(req);
                   if(isMultipart){
                        System.out.println("is MultiPart");
                        DiskFileUpload upload = new DiskFileUpload();
                        List fileList = upload.parseRequest(req);
                        InputStream uploadedFileStream = null;
                        String uploadedFileName = null;
                        ArrayList impArray = new ArrayList();
                        Iterator iter = fileList.iterator();
                        while (iter.hasNext()) {
                             System.out.println("inside while");
                             FileItem item = (FileItem) iter.next();
                             if (!item.isFormField()) {
                                  System.out.println("item is not form field");
                                  if (item.getSize() < 1)
                                       throw new Exception("No file was uploaded");
                                  else
                                       uploadedFileName = item.getName();
                                       System.out.println("uploaded file name "+uploadedFileName);
                                       System.out.println("uploaded file size is "+item.getSize());
                                       uploadedFileStream = item.getInputStream();
                                       System.out.println("uploaded input stream available size is "+uploadedFileStream.available());
                             else
                                  System.out.println("item is form field");
                                  String key     = item.getFieldName();
                                  String value = item.getString();
                                  System.out.println("key is"+key);
                                  System.out.println("value is"+value);
                                  if(key.equals("projectId2")){
                                       projIdValue = value;
                        System.out.println("outside while");
                        POIFSFileSystem fs = new POIFSFileSystem(uploadedFileStream);
                        System.out.println("got POIFSFileSystem");//this is been printed in logs
                        HSSFWorkbook wb = new HSSFWorkbook(fs);//it is breaking over here
                        System.out.println("got HSSFWorkbook");//this is not been printed in logs
                        HSSFSheet sheet = wb.getSheetAt(0);
                        System.out.println("got HSSFSheet");
                        Iterator rows = sheet.rowIterator();
                        if(rows.hasNext()){
                        while( rows.hasNext() ) {
                             System.out.println("rows iteration");
                             HSSFRow row = (HSSFRow) rows.next();
                             Iterator cells = row.cellIterator();
                             while( cells.hasNext() ) {
                                  System.out.println("cell iteration");
                                  HSSFCell cell = (HSSFCell) cells.next();
                                  HashMap hm = new HashMap();//if everything is fine i'll use this hashmap to store values
                             System.out.println("CES UPLOAD.SERVLET. After adding");
                             msg = "Attendees have been added successfully";
                             req.setAttribute("msgText", msg);
                             targetPage = "/ces_disp.jsp";
                        else
                             throw new Exception("The Excel Sheet Uploaded has no entries. Please check and try again");
                   else{
                        throw new Exception("The Form is not Multipart");
              catch (Exception e)
                   System.out.println("CES UPLOAD.SERVLET.EXCEPTION ::: Exception");
                   targetPage = "/ces_disp.jsp";
                   if(e != null) req.setAttribute("msgText", e.getMessage());
                   else req.setAttribute(Constants.EXCEPTION_ATTR_NAME, new Exception("Unknown Exception"));
                   e.printStackTrace();
              finally{
                   System.out.println("CES UPLOAD.SERVLET. ::: Finally");
                   ServletContext stx = getServletConfig().getServletContext();
                   RequestDispatcher dispatcher = sCx.getRequestDispatcher(targetPage);
                   dispatcher.forward(req, res);
    Message was edited by: Noufal
    Noufal_k
    Message was edited by:
    Noufal_k

    import org.w3c.dom.* ;
    import java.io.FileInputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import jxl.*;
    import org.apache.commons.fileupload.*;
    import org.apache.commons.fileupload.disk.*;
    import org.apache.commons.fileupload.servlet.*;
    import org.apache.poi.poifs.filesystem.POIFSFileSystem;
    import org.apache.poi.hssf.usermodel.HSSFCell;
    import org.apache.poi.hssf.usermodel.HSSFSheet;
    import org.apache.poi.hssf.usermodel.HSSFWorkbook;
    import org.apache.poi.hssf.usermodel.HSSFRow;
    public class CescoreUploadServlet extends baseHttpServlet
    private DataSource cesDS = null;
    public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    doPost(req, res);
    public void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
    //including only relevant code
    String targetPage = null;
    System.out.println("Upload Controller");
    HttpSession session = req.getSession(true);
    try
    String projIdValue = null;
    String msg = null;
    boolean isMultipart = FileUpload.isMultipartContent(req);
    if(isMultipart){
    System.out.println("is MultiPart");
    DiskFileUpload upload = new DiskFileUpload();
    List fileList = upload.parseRequest(req);
    InputStream uploadedFileStream = null;
    String uploadedFileName = null;
    Iterator iter = fileList.iterator();
    while (iter.hasNext()) {
    System.out.println("inside while");
    FileItem item = (FileItem) iter.next();
    if (!item.isFormField()) {
    System.out.println("item is not form field");
    if (item.getSize() < 1)
    throw new Exception("No file was uploaded");
    else
    uploadedFileName = item.getName();
    System.out.println("uploaded file name "+uploadedFileName);//printing  c:/excelsheets/fileToUpload.xls
    System.out.println("uploaded file size is "+item.getSize());//printing size is 15872
    uploadedFileStream = item.getInputStream();
    System.out.println("uploaded input stream available size is "+uploadedFileStream.available());//printing available input stream size is 15872
    else
    System.out.println("item is form field");
    String key = item.getFieldName();
    String value = item.getString();
    System.out.println("key is"+key);
    System.out.println("value is"+value);
    if(key.equals("projectId2")){
    projIdValue = value;
    System.out.println("outside while");
    POIFSFileSystem fs = new POIFSFileSystem(uploadedFileStream);
    System.out.println("got POIFSFileSystem");//this is been printed in logs
    HSSFWorkbook wb = new HSSFWorkbook(fs);//it is breaking over here
    System.out.println("got HSSFWorkbook");//this is not been printed in logs
    HSSFSheet sheet = wb.getSheetAt(0);
    System.out.println("got HSSFSheet");
    Iterator rows = sheet.rowIterator();
    if(rows.hasNext()){
    while( rows.hasNext() ) {
    System.out.println("rows iteration");
    HSSFRow row = (HSSFRow) rows.next();
    Iterator cells = row.cellIterator();
    while( cells.hasNext() ) {
    System.out.println("cell iteration");
    HSSFCell cell = (HSSFCell) cells.next();
    HashMap hm = new HashMap();//if everything is fine i'll use this hashmap to store values
    System.out.println("CES UPLOAD.SERVLET. After adding");
    msg = "Attendees have been added successfully";
    req.setAttribute("msgText", msg);
    targetPage = "/ces_disp.jsp";
    else
    throw new Exception("The Excel Sheet Uploaded has no entries. Please check and try again");
    else{
    throw new Exception("The Form is not Multipart");
    catch (Exception e)
    System.out.println("CES UPLOAD.SERVLET.EXCEPTION ::: Exception");
    targetPage = "/ces_disp.jsp";
    if(e != null) req.setAttribute("msgText", e.getMessage());
    else req.setAttribute(Constants.EXCEPTION_ATTR_NAME, new Exception("Unknown Exception"));
    e.printStackTrace();
    finally{
    System.out.println("CES UPLOAD.SERVLET. ::: Finally");
    ServletContext stx = getServletConfig().getServletContext();
    RequestDispatcher dispatcher = stx.getRequestDispatcher(targetPage);//throwing null pointer exception for this line
    dispatcher.forward(req, res);
    }

  • About the finally block of the try catch.

    I know that finally block contains the code that will be executed in any condition of the try catch.
    However, I think it is unneccessary, since the stack after the try catch stack will be executed any way.
    Any one can help?
    for example
    try{
    System.in.read();
    catch(Exception e){}
    finally
    { System.out.println("does this matter?");}and
    try{
    System.in.read();
    catch(Exception e){}
    System.out.println("does this matter?");

    However, I think it is unneccessary, since the stackafter the try catch
    stack will be executed any way.That does assume that you catch and handle the error
    appropriately.
    Of course this is valid as well, and demonstrates
    when you would WANT a finally clause.
    Connection con = null;
    Statement stmt = null;
    try{
    con  = Database.getConnection();
    stmt = con.createStatement("Select * from dual");
    // maybe something throws an exception here?
    finally{
    if (stmt != null){
    stmt.close();
    if (con != null){
    con.close();
    The finally block here might throw a null pointer exception itself use
    null!=stmt null!=stmt

Maybe you are looking for