Stoping processing after a finally block

I have a code
try{
}catch(){
}finally(){
How can I stop the process at this stage if there is any Exceptions above
try{
}catch{

The question isn't as clear as it could be, but what I
think you're saying is that you don't want the code in
the finally block to be executed if there is an
exception thrown. Is that what you're after? If it is,
then why are you using a finally block?:
E.g., instead of
try {
//try code
catch (MyException e) {
//catch code
finally {
//after try code
}use:
boolean exceptionThrown = false;
try {
//try code
catch (MyException e) {
exceptionThrown = true;
//catch code
if (!exceptionThrown) {
//after try code
}Depending on whether you are rethrowing the exception
or returning from within the catch block, you may or
may not need the exceptionThrown flag.
If this deoesn't help, could you please clarify the
question.I think this is the best way to solve the problem. But it would have definitely helped a lot if the problem statement would have been more clear.
Vijay

Similar Messages

  • Finally block is optional??

    I want to know if finally block is optional? I tested this myself, and
    the following yield the same output.
    void f()
         try
         { //code1
         catch()
         finally
         { //code2
    void f()
         try
         { //code1
         catch()
         //code2
    please advise. thanks!!

    I'm not sure what you're asking, and your sample code tells us almost nothing, but I'll take a guess.
    You're thinking finally doesn't do anything, because you can just put the code after the catch block, right?
    Here's some more realistic code: void foo() throws IOException {
        InputStream ins = null;
        try {
            Bar bar = new Bar(); // this might throw BarException
            ins = bar.getAnInputStream();
            ins.read(); // etc.
            // do stuff with what we read from ins
        catch (BarException exc) {
            // log, handle, whatever
        finally {
            // cleanup, for example ins.close();
        // OR we could cleanup here, you think, right?
    } If the try block completes without any problems, or if a BarException is thrown and we don't rethrow anything from the catch block, then, yes, you could put the cleanup after the finally block.
    However, what happens if bar.getAnInputStream() returns null? Or if there's an IOException creating or reading the stream? In that case, we jump out of our try block as soon as the exception occurs--the IOException or the NPE if we try to call read() on a null stream reference.
    In this case the try block stops what it's doing and control passes to the finally block, after which we leave the method (well, leave the try statement for the next enclosing try, but there isn't one in this method, so we leave the method).
    If we throw an uncaught exception (anything other than IOE, in this example) or even if we call return from inside the try block, the finally block will always be executed. The code following the finally block won't be executed in these cases.
    ¶

  • Validation Fails - BadPaddingException: Given final block not property padded

    I'm following the Quick-Start Guide step-by-step and get the following message when I run Validator.bat from section "4. Setup & deploy..."
    C:\Users\Charles\Desktop\FlashAccess2_0_2\Flash Access Server for Protected Stre
    aming>Validator -g -r C:\Tomcat\licenseserver
    Validating global deployment ...
            Validating partition deployment - flashaccessserver...
                    Validating tenant deployment - flashaccessserver/sampletenant...
    javax.crypto.BadPaddingException: Given final block not properly padded
            at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
            at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
            at com.sun.crypto.provider.SunJCE_ab.b(DashoA13*..)
            at com.sun.crypto.provider.PBEWithMD5AndDESCipher.engineDoFinal(DashoA13
            at javax.crypto.Cipher.doFinal(DashoA13*..)
            at com.adobe.flashaccess.server.license.configuration.commonsadapter.Scr
    ambleUtil.decode(ScrambleUtil.java:83)
            at com.adobe.flashaccess.server.license.configuration.commonsadapter.Scr
    ambleUtil.unscramble(ScrambleUtil.java:51)
            at com.adobe.flashaccess.server.license.configuration.commonsadapter.Ten
    antConfigurationImpl$CryptographyImpl.readCredentials(TenantConfigurationImpl.ja
    va:583)
            at com.adobe.flashaccess.server.license.configuration.commonsadapter.Ten
    antConfigurationImpl$CryptographyImpl.<init>(TenantConfigurationImpl.java:516)
            at com.adobe.flashaccess.server.license.configuration.commonsadapter.Ten
    antConfigurationImpl.<init>(TenantConfigurationImpl.java:108)
            at com.adobe.flashaccess.server.license.configuration.commonsadapter.Com
    monsConfigurationBasedFactory.getTenantConfiguration(CommonsConfigurationBasedFa
    ctory.java:89)
            at com.adobe.flashaccess.server.license.tools.Validator.validateTenantDe
    ployment(Validator.java:255)
            at com.adobe.flashaccess.server.license.tools.Validator.validatePartitio
    nDeployment(Validator.java:283)
            at com.adobe.flashaccess.server.license.tools.Validator.validateGlobalDe
    ployment(Validator.java:301)
            at com.adobe.flashaccess.server.license.tools.Validator.process(Validato
    r.java:173)
            at com.adobe.flashaccess.server.license.tools.Validator.main(Validator.j
    ava:117)
    Failed to validate tenant deployment 'flashaccessserver/sampletenant' - null
    See log for details:
    (C:\Users\Charles\AppData\Local\Temp\temp82526431968521948758558823183500\flasha
    ccessserver\flashaccess-partition.log)

    Hi Safdar,
    It's a very valid question, considering the confusion I had with the different scramblers...
    This is what I am using:
    For the license server I used the scrambler in "Flash Access Server for Protected Streaming". After passing the parameters directly to the jar (and not as parameters to the batch file) I get the same result on Windows and on Linux. I use this value in flashaccess-tenant.xml on both Windows and Linux and the license servers work correctly on both platforms.
    The problems are on the packager. I am using Flash Access Manager running on a windows machine to configure both packagers (the one on Windows and the one on Linux). I have the same certificates installed on both machines. For both configurations I enter the same password, and when I save the configuration both flashaccess-refimpl-packager.properties files show the same scrambled value. However, the packager on Windows works fine, but on Linux I get the BadPaddingException error.
    Is this clearer?
    Am I worng to assume I can run Flash Access Manager on a windows machine and use it to configure and run a packager on a Linux machine? Is there a way to run the Flash Access Manager on Linux?
    Thanks,
    - Naomi

  • Question about scoping finally blocks

    Hello All,
    I have a piece of code here that has been tricky for me to do a finally block on and it suddenly occured to me that I have maybe been going about exceptions the wrong way. So generally with this type of situation I'll just declare the variable somewhere else above the try and when i do that the scope makes me able to finally block it. Here I can't do that because the declaration actually requires it to have an initial value and it throws it's own exception as a filereader. Sorry about the newb question, but what's the proper way to block out the exceptions and finally block for this code snippet?
    Thanks in advance!
    Josh
    public static void setParameters(File fileName)
              try
                   File fileForProcessing=new File(fileName.getAbsolutePath());
                   //wrap the file in a filereader and buffered reader for maximum processing
                   FileReader theReader=new FileReader(fileForProcessing);
                   BufferedReader bufferedReader=new BufferedReader(theReader);
                   //fill in data into the tempquestion variable to be populated
                   //Set the question and answer texts back to default
                   questionText="";
                   answerText="";
                   //Define the question variable as a Stringbuffer so new data can be appended to it
                   StringBuffer endQuestion=new StringBuffer();
                   String tempQuestion="";
                   //Define new file with the absolutepath and the filename for use in parsing out question/answer data
                   tempQuestion=bufferedReader.readLine();
                   //while there are more lines append the stringbuffer with the new data to complete the question buffer
                   while(tempQuestion!=null)
                        endQuestion.append(tempQuestion);
                        tempQuestion=bufferedReader.readLine();
                   //Set the answer to the stringbuffer after converting to string
                   answerText=endQuestion.toString();
                   //code to take the filename and replace _ with a space and put that in the question text
                   char theSpace=' ';
                   char theUnderline='_';
                   questionText=(fileName.getName()).replace(theUnderline, theSpace);
              catch(FileNotFoundException exception)
                   logger.log(Level.WARNING,"The File was Not Found\n"+exception.getMessage()+"\n"+exception.getStackTrace(),exception);
              catch(IOException exception)
                   logger.log(Level.SEVERE,exception.getMessage()+"\n"+exception.getStackTrace(),exception);
              finally
                   try
                   theReader.close();
                   catch(Exception e)
         }

    Here I can't do that
    because the declaration actually requires it tohave
    an initial value No, it doesn't.Yes it does. But that value can be and should be
    null.I suspect it would be more accurate to say that dereferencing the variable in the finally block requires definite assignment. The declaration itself doesn't require it at all and in fact assignment could be deferred. However, just assigning null in the declaration is still probably the best idea.
    FileReader theReader = null;
    try {
        // yadda yadda
    } finally {
       if (theReader != null) {
           theReader.close();
    }

  • Time-Out for Process with Correlation - Avoiding blocked Queues

    Hello,
    I have the following requirement, it would be great if you could share your opinions and knowledge on it:
    If have an integration process which opens a correlation and sends out an asynchronous request message. The response normally arrives after 10 minutes and is correlated to the process using a correlationID that has been activated by the request message. Additionally there is a deadline branch which terminates the process after 1 hour.
    So far this works fine.
    However there might be some very rare cases where a response is delayed (e.g. if there is maintenace work on partner side). So it could be the case that a response arrives a day later when the process instance is already terminated:
    My questions are now:
    1. How can I avoid that the inbound queue is blocked with the response message that cannot find an active correlation?
    2. Best thing would be to store the response message on the file system in case no more active correlations are open.
    So basically the logic could be:
    If message arrives, check whether process instance with corresponding correlation is active, if yes then send to process, if no send to file receiver.
    Is this possible?

    Thread closed - no solution so far.

  • 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

  • Prb in using finally block......please help.

    hi currently i am facing this problem when i tried using finally block. after recompile, it gave me a warning message or should i said is an error message. My error statement is as below,
    C:\EKP\web\WEB-INF\classes\com\tms\report\model\ReportModule.java:393: warning: finally clause cannot complete normally
    ^
    Note: C:\EKP\web\WEB-INF\classes\com\tms\report\model\ReportModule.java uses or overrides a deprecated API.
    Note: Recompile with -deprecation for details.
    1 warning
    my code is as below,
    try
    service.deleteJobTask( task );
    service.scheduleJob( task, schedule );
    success = true;
    catch( SchedulingException e )
    Log.getLog( getClass() ).error( e.getMessage(), e );
    finally
    return success;
    Please help me. Thank you very much
    Regards.

    Ditch the return statement in your finally clause and move it to the end of the try block in stead. The whole idea behind finally is that it is always executed even after you return from the method, you don't add a return statement to your finally.
    In your case you don't need a finally clause, you only add calls to it that MUST be executed, such as freeing up resources.

  • AES -javax.crypto.BadPaddingException: Given final block notproperly padded

    I have an Encrypt Util class to encrypt and decrypt CLOB content in the database(Oracle). During encryption there is no error/exception thrown., But while decryption it throws the exception javax.crypto.BadPaddingException: Given final block notproperly padded.
    The error is thrown only for selected records, not for all. For most of them it works fine. I use 256 bit AES Encryption.The sequence of steps to generate and retrieve the key is as follows:
    (Generating and Storing the Key)
    Generate original Key Using JCE --> Then XOR it with a known String (Key) --> Write to a file in DB Server (Solaris 10) using a Stored Procedure.
    (Retrieving the Key)
    Read the key file using s Stored Procedure --> XOR it with known String(Key) --> Retrieve the original Key
    The decryption works fine for most of the records (70%) but failing 30% of the time. There is no exception in the way the encrypted content gets stored in the db
    The key is generated as a one time step in the application and stored in the file. It is retrieved and cached in the application once, everytime the appserver is restarted.
    Could someone pls. help?
    Attaching below (1) code snippet for generating the key and (2) The code snipped to retrieve the key (3) the class which does the encryption and decryption of data
    (1) code snippet for generating the key
    String xorRefKey = "*&^%$#@!AiMsKey!*&^%$#@!AiMsKey!";
    KeyGenerator kg = KeyGenerator.getInstance("AES");
                kg.init(256);
                String initialKey = new String (kg.generateKey().getEncoded());
             char[] refArr =  xorRefKey.toCharArray();
              char[] initKeyArr = initialKey.toCharArray();
                char[] finalKeyArr = new char[refArr.length];
                 for(int i=0;i<initKeyArr.length;i++){
                     finalKeyArr= (char)(initKeyArr[i] ^ refArr[i]);
    String finalKey = new String(finalKeyArr);----------------------
    (2) The code snipped to retrieve the keyString xorRefKey = "*&^%$#@!AiMsKey!*&^%$#@!AiMsKey!";
    char[] refArr = xorRefKey.toCharArray();
    //initialKey is the key read from the file using a db call
    char[] initKeyArr = initialKey.toCharArray();
    char[] finalKeyArr = new char[refArr.length];
    for(int i=0;i<initKeyArr.length;i++){
    finalKeyArr[i]= (char)(initKeyArr[i] ^ refArr[i]);
    String finalKey= new String(finalKeyArr);
    Class to encrypt/decrypt
    (3) EncryptUtil classpublic class EncryptUtil {
    private static SecretKeySpec skeySpec = null;
    private static final String encryptionAlgorithm = "AES";
    private static IGOLogger logger = IGOLogger.getInstance(IGOLogger.ENCRYPTION);
    private static final String UNICODE_FORMAT = "UTF8";
    private Cipher cipher = null;
    public EncryptUtil(String key){
    String lFuncName = "EncryptUtil :: EncryptUtil(): ";
    try{
    cipher = Cipher.getInstance(encryptionAlgorithm);
    skeySpec = new SecretKeySpec(key.getBytes(), encryptionAlgorithm);
    } catch (NoSuchAlgorithmException e) {
    logger.error(lFuncName + "No Such Algorithm Error while creating Cipher and KeySpec ",e);
    } catch (NoSuchPaddingException e) {
    logger.error(lFuncName + "No Such Padding Error while creating Cipher and KeySpec ",e);
    * Encrypts the data based on the key and algorithm
    * @param data
    * @return encrypted data
    public String encrypt(String data){
    String lFuncName = "EncryptUil :: encrypt(): ";
    byte[] encryptedData = null;
    String encryptedFinal = "";
    try{
    if(data!=null && data.length()>0){
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec,cipher.getParameters());
    encryptedData = (cipher.doFinal(data.getBytes(UNICODE_FORMAT)));
    encryptedFinal = new BASE64Encoder().encode(encryptedData);
    } catch (InvalidKeyException e) {
    logger.error(lFuncName + "Invalid Key Error while Encrypting Data ",e);
    } catch (BadPaddingException e) {
    logger.error(lFuncName + "Bad Padding Error while Encrypting Data ",e);
    } catch (IllegalBlockSizeException e) {
    logger.error(lFuncName + " Illegal Block Size Error while Encrypting Data ",e);
    } catch (InvalidAlgorithmParameterException e) {
    logger.error(lFuncName + " Invalid Alogirthm Parameter Error while Encrypting Data ",e);
    } catch (UnsupportedEncodingException e) {
    logger.error(lFuncName + " Unsupported Encoding Exception Error while Encrypting Data ",e);
    }catch(Exception e){
    logger.error(lFuncName + " Error while Encrypting Data ",e);
    return encryptedFinal;
    * Decrypts the encrypted data based on the key and algorithm
    * @param data
    * @return
    public String decrypt (String data){
    String lFuncName = "EncryptUil :: decrypt(): ";
    byte[] decrypted = null;
    byte[] decryptedFinal = null;
    String decryptedData = "";
    try{
    if(data!=null && data.length()>0){
    cipher.init(Cipher.DECRYPT_MODE, skeySpec);
    decrypted = new BASE64Decoder().decodeBuffer(data);
    decryptedFinal = (cipher.doFinal(decrypted));
    decryptedData = this.bytes2String(decryptedFinal);
    } catch (InvalidKeyException e) {
    logger.error(lFuncName + "Invalid Key Error while Decrypting Data ",e);
    } catch (BadPaddingException e) {
    logger.error(lFuncName + "Bad Padding Error while Decrypting Data ",e);
    } catch (IllegalBlockSizeException e) {
    logger.error(lFuncName + " Illegal Block Size Error while Decrypting Data ",e);
    } catch (IOException e) {
    logger.error(lFuncName + " IO Exception while Decrypting Data ",e);
    }catch (Exception e){
    logger.error(lFuncName + " Error while Decrypting Data ",e);
    return decryptedData;
    private String bytes2String( byte[] bytes )
              StringBuffer stringBuffer = new StringBuffer();
              for (int i = 0; i < bytes.length; i++)
                   stringBuffer.append( (char) bytes[i] );
              return stringBuffer.toString();
    }The EncryptUtil is invoked as follows:EncryptUtil encryptUtil = new EncryptUtil("finalKey retrieved when application starts");
    encryptUtil.encrypt(unencryptedData);                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                       

    shannara wrote:
    thanks for your reply.
    I am sorry but I am not able to get you exactly. Every time I invoke the Utility class, I do a
    EncryptUtil eUtil = new EncryptUtil() Good. You seem to be using it in a thread safe manner since you create a new instance each time you need to use one.
    >
    and then invoke the decrypt() or encrypt() method, which gets the key from the cache (it is a read only object, so no problems of concurrent modification or any thing of that sort). And also these methods are called from a normal java class only, which inturn may be called from a jsp/servlet, but no scenarios of any concurrent access as such, so based on what you said, I am not able to figure out where exactly the thread safety could come as an issue.Each instance of a jsp or servlet can be being processed by many threads at the same time. Your statement above hints at a possible lack of understand on this point though I could be just reading it wrong. It indicates to me that your problem may be nothing to do with the encryption and everything to do with 'concurrent access' .
    Make sure you have no instance variables or class variables in your jsp(s) and servlet(s).
    Edit: The more I think about this the more I believe you have a thread safety problem in the code that reads the key. I would concentrate on that.
    Edited by: sabre150 on Dec 18, 2007 10:10 AM

  • Given final block not properly not padded.....when given wrong password....

    hi..........sir
    when i am executing the following code..with wrong password....i am getting the BadPaddingException:Given final block not properly padded............
    plz help me to solve this one with the solution.
    I am doing my final project .....i am implementing an security protocol....
    here is thecode...
    String pw=JOptionPane.showInputDialog("enter the password string");
    byte[] pwb=new byte[pw.getBytes().length];
    pwb=pw.getBytes();
    String msg=JOptionPane.showInputDialog(null,"enter the message");
    byte[] msgb=new byte[msg.getBytes().length];
    msgb=msg.getBytes();
    try
    PBEKeySpec ks=new PBEKeySpec(pw.toCharArray());
    SecretKeyFactory skf= SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey ky=skf.generateSecret(ks);
    MessageDigest md=MessageDigest.getInstance("MD5");
    md.update("srikrishna".getBytes());byte[] digest=md.digest();
    byte salt[]=new byte[8];
    for(int i=0;i<8;i++)
         salt=digest[i];
    PBEParameterSpec ps=new PBEParameterSpec(salt,20);
    Cipher cf=Cipher.getInstance("PBEWithMD5AndDES");
    cf.init(Cipher.ENCRYPT_MODE,ky,ps);
    byte[]thCp=cf.doFinal(msgb);
    for(int i=0;i<thCp.length;i++)
         System.out.print((char)thCp[i]);
    System.out.println("\n\n");
    String pwbs=JOptionPane.showInputDialog("enter the password string");
    byte[] pwbsb=new byte[pwbs.getBytes().length];
    pwbsb=pwbs.getBytes();
    PBEKeySpec ks1=new PBEKeySpec(pwbs.toCharArray());
    SecretKeyFactory skf1= SecretKeyFactory.getInstance("PBEWithMD5AndDES");
    SecretKey ky1=skf1.generateSecret(ks1);
    MessageDigest md1=MessageDigest.getInstance("MD5");
    md1.update("srikrishna".getBytes());byte[] digest1=md1.digest();
    byte salt1[]=new byte[8];
    for(int i=0;i<8;i++)
         salt1[i]=digest1[i];
    PBEParameterSpec ps1=new PBEParameterSpec(salt1,20);
    Cipher cf1=Cipher.getInstance("PBEWithMD5AndDES");
    cf1.init(Cipher.DECRYPT_MODE, ky1,ps1);
    byte[]thPt=cf1.doFinal(thCp);
    for(int i=0;i<thPt.length;i++)
         System.out.print((char)thPt[i]);
    catch(Exception e)
         e.printStackTrace();
    Thanks in Advance.............
    Edited by: hareksna on Jan 12, 2009 4:36 PM

    hareksna wrote:
    sir, thanks for reply.........
    I understood .....
    sorry if am asking u once again.......
    for every encrypted data there will be an corresponding decrypted data.........even with the different key.....it shud produce some decrypted bytes.(even diff from plain text)......naa.....i.e it should produce the wrong plain text.......The encyption process -
    cleartext (adding padding) padded cleartext (encrypting) ciphertext.
    The decryption process -
    ciphertext (decrypting) padded cleartext (remove padding) cleartext.
    Even though it would be gibberish when the wrong key is used, you seem to want access to the 'padded cleartext' but using your code you do not have access to it. You could emulate the PBE process and get access to the 'padded cleartext' but what would be the point. You would just have gibberish when using the wrong key.
    but y the exception......
    ok ......and also tell me y this BPE is actually happens and how to avoid that when we use some padding.....
    plz tell me the reason.............Start by reading "Applied Cryptography"by Bruce Schneier and then "Practical Cryptography" by Ferguson and Schneier.
    >
    so finally .........
    u r saying that i need to catch the BPE and should inform client that he entered wrong password........
    so i have to end up in the second step itself.....
    is there any other way to perfom this one?......if there, plz let me know....if any alternative.....As I said earlier, the alternative is to emulate the PBE process yourself but what would be the point. You would just end up with gibberish if you use the wrong password.
    P.S. You won't always get a bad padding exception if you use the wrong password. About 1in 256 you will just get gibberish as the result without the exception.
    P.P.S. Your keyboard seems to have a problem with it's '.' key. In your place I would get it fixed because the perpetual '......' annoys the hell out of many people who respond to these forums.
    P.P.P.S. Your 'caps' key seems to be intermittently broken. Please get if fixed.
    P.P.P.P.S. You should turn off your computer's SMS mode. Using 'u' instead of 'you' makes your posts very difficult to read and it annoys the hell out of many people who respond to these forums.

  • Given final block not properly padded

    I am working on an application that sends encrypted data over the network using Blowfish. I developed a simple server and client to test and I getting this error when I try to decrypt the cypher in the server. Here is what I do:
    This happens on the client side:
    I encrypt my message with this method
    public byte[] encryptedMessage() throws Exception{
            KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
            keyGenerator.init(128);     
            Key key = keyGenerator.generateKey();
            Cipher cipher = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] plaintext = getMessage().getBytes("UTF8");
            byte[] ciphertext = cipher.doFinal(plaintext);
            return ciphertext;
        }Then send it to the server like this:
    //get my cypher from the method shown before
    cipher = mc.encryptedMessage();
    //put the cypher in this simple object          
    InformationShared cipherToSend = new InformationShared(cipher.length);
    cipherToSend.setMessage(cipher);
    //Send it accross through the network
    Socket socket =  new Socket("127.0.0.1",8085);
    ObjectOutputStream out = new ObjectOutputStream(socket.getOutputStream());
    out.writeObject(cipherToSend);This is what happens in the server side:
    //Get the incoming object
    ObjectInputStream in = new ObjectInputStream( incoming.getInputStream() );
    //downcast the object
    InformationShared cipherIn = (InformationShared)in.readObject();
    //decypher the message  in the decypher method             
    String result = decypher(cipherIn.getMessage());
    //This is the decipher method
    public String decypher(byte cipherIn[]) throws Exception{
               KeyGenerator keyGenerator = KeyGenerator.getInstance("Blowfish");
               keyGenerator.init(128);     // need to initialize with the keysize
               Key key = keyGenerator.generateKey();
               Cipher ciph = Cipher.getInstance("Blowfish/ECB/PKCS5Padding");
               ciph.init(Cipher.DECRYPT_MODE, key);
               // Perform the decryption
               byte[] decryptedText = ciph.doFinal(cipherIn);
               String output = new String(decryptedText,"UTF8");;
               return output;
            }The error happens in the decypher method in this line:
    byte[] decryptedText = ciph.doFinal(cipherIn);Thanks for any help!

    Hi
    I am woriking on an web application that send Encrypted data over the network and stores into the databse.After that I want to retrieve that data from database then I want decrypt it by using DES.
    After Encryting It is storing properly into the database but while retriving from database and want to decrypt it the It is giving exception like "javax.crypto.BadPaddingException: Given final block not properly padded"
    For Encryption I am using one bean class tha are
    package EncryptBean;
    import java.util.*;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.spec.*;
    import com.sun.crypto.provider.*;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.Cipher;
    import java.security.NoSuchAlgorithmException;
    import java.security.InvalidKeyException;
    import java.security.InvalidAlgorithmParameterException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.BadPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import sun.misc.BASE64Encoder;
    import sun.misc.BASE64Decoder;
    import javax.crypto.*;
    public class DesEncrypterBean {
    Cipher ecipher;
    Cipher dcipher;
    public DesEncrypterBean(SecretKey key) {
    try {
    ecipher = Cipher.getInstance("DES");
    dcipher = Cipher.getInstance("DES");
    ecipher.init(Cipher.ENCRYPT_MODE, key);
    dcipher.init(Cipher.DECRYPT_MODE, key);
    } catch(javax.crypto.NoSuchPaddingException e)
         {System.out.println("NoSuchPaddingException : "+e);     
                } catch (java.security.NoSuchAlgorithmException e)
    {System.out.println("NoSuchAlgorithmException : "+e);     
                } catch (java.security.InvalidKeyException e)
    {System.out.println("InvalidKeyException : "+e); }
    public String encrypt(String str) {
    try {
    // Encode the string into bytes using utf-8
    byte[] utf8 = str.getBytes("UTF8");
    // Encrypt
    byte[] enc = ecipher.doFinal(utf8);
    // Encode bytes to base64 to get a string
    return new sun.misc.BASE64Encoder().encode(enc);
    } catch (javax.crypto.BadPaddingException e) {
    System.out.println("encrypt BadPaddingException : "+e);
    } catch (IllegalBlockSizeException e) {
    System.out.println(" encrypt IllegalBlockSizeException : "+e);
    } catch (UnsupportedEncodingException e) {
    System.out.println("encrypt UnsupportedEncodingException : "+e);
    } catch (java.io.IOException e) {
    System.out.println("encrypt IOException : "+e);
    } return null;
    public String decrypt(String str) {
    try {
    // Decode base64 to get bytes
    // byte[] utf8 = str.getBytes("UTF8");
    byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
    // Decrypt
    byte[] utf8 = dcipher.doFinal(dec);
    // Decode using utf-8
    return new String(utf8, "UTF8");
    } catch (javax.crypto.BadPaddingException e)
         {System.out.println("encrypt BadPaddingException : "+e);
                } catch (IllegalBlockSizeException e) {
    System.out.println("encrypt IllegalBlockSizeException : "+e);
    } catch (UnsupportedEncodingException e) {
    System.out.println("encrypt UnsupportedEncodingException : "+e);
    }catch (java.io.IOException e) {
    System.out.println("encrypt IOException : "+e);
    return null;
    ** By using bellow screen I am retrieving the data from screen and encrypting it and sended to the database I is working properly
    import EncryptBean.DesEncrypterBean;
    import java.util.*;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.spec.*;
    import com.sun.crypto.provider.*;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.Cipher;
    import java.security.NoSuchAlgorithmException;
    import java.security.InvalidKeyException;
    import java.security.InvalidAlgorithmParameterException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.BadPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import sun.misc.BASE64Encoder;
    import javax.crypto.*;
    public class Secure_Encrypt extends HttpServlet
              Connection con=null;
              Statement stmt=null;
              Cipher ecipher;
    Cipher dcipher;
              String uname=null,pwd=null;
              ServletOutputStream sos;
              SecretKey key=null;
    public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException,IOException
    uname=req.getParameter("username");               pwd=req.getParameter("password");
    try
    Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con=DriverManager.getConnection("jdbc:odbc:GMT","sa","iqm");
    stmt=con.createStatement();
    sos=res.getOutputStream();
    // Generate a temporary key. In practice, you would save this key.
    // See also e464 Encrypting with DES Using a Pass Phrase.
    key = KeyGenerator.getInstance("DES").generateKey();
    // Create encrypter/decrypter class
    DesEncrypterBean encrypter = new DesEncrypterBean(key);
    // Encrypt
    String encrypted = encrypter.encrypt(uname);
    System.out.println("Don't tell anybody! "+encrypted);
    stmt.execute("insert into Admin(UserName,Passward) values('"+encrypted+"','"+encrypted+"')");
    System.out.println("......record saved");
    sos.println("Record Saved : "+encrypted);
    catch(Exception e)
    {System.out.println("Exception in login" +e);}
    In above Programe Woking Properly
    ** Bellow programe using for retrieving data from database.After retrieving data I want Decrypt it but not working properly
    import EncryptBean.DesEncrypterBean;
    import java.util.*;
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import java.sql.*;
    import java.security.*;
    import java.security.spec.*;
    import javax.crypto.spec.*;
    import com.sun.crypto.provider.*;
    import javax.crypto.KeyGenerator;
    import javax.crypto.SecretKey;
    import javax.crypto.Cipher;
    import java.security.NoSuchAlgorithmException;
    import java.security.InvalidKeyException;
    import java.security.InvalidAlgorithmParameterException;
    import javax.crypto.NoSuchPaddingException;
    import javax.crypto.BadPaddingException;
    import javax.crypto.IllegalBlockSizeException;
    import sun.misc.BASE64Encoder;
    import javax.crypto.*;
    public class Secure extends HttpServlet
              Connection con=null;
              Statement stmt=null;
              Cipher ecipher;
    Cipher dcipher;
              String uname=null,pwd=null;
              ServletOutputStream sos;
              SecretKey key=null;
    public void doPost(HttpServletRequest req, HttpServletResponse res)throws ServletException,IOException
    try
    {Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
    con=DriverManager.getConnection("jdbc:odbc:GMT","sa","iqm");
    stmt=con.createStatement();
    ResultSet rs=stmt.executeQuery("select UserName,Passward from Admin");
    while(rs.next())
         uname=rs.getString(1);
         pwd=rs.getString(2);
    sos=res.getOutputStream();
    // Generate a temporary key. In practice, you would save this key.
    // See also e464 Encrypting with DES Using a Pass Phrase.
    key = KeyGenerator.getInstance("DES").generateKey();
    // Create encrypter/decrypter class
    DesEncrypterBean encrypter = new DesEncrypterBean(key);
    // Decrypt
    uname=uname.trim();
    String decrypted = encrypter.decrypt(uname);
    System.out.println("Original message is! "+decrypted);
    }catch(Exception e)
    {System.out.println("Exception in login" +e);
    In above Programe giving Exception " javax.crypto.BadPaddingException: Given final block not properly padded"
    Please analyze my application and send me suitable solution for decryption
    one more thing When I encrypting that time KeyGenerator generating one key.same as when I Decrypting that time also KeyGenerator generating one key but both are not same.
    How can we generate both key are same

  • Given final block not properly padded : PLEASE HELP!!

    hi guys
    please can you help me with the following error that i am getting.
    i appear to be encyrpting ok as image a am readin in and the file reading out are the same size.
    but i am getting this pading error. been at it all day and cant find the answer to this error.
    Exception: javax.crypto.BadPaddingException: Given final block not properly padd
    ed
    javax.crypto.BadPaddingException: Given final block not properly padded
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.SunJCE_f.b(DashoA13*..)
    at com.sun.crypto.provider.AESCipher.engineDoFinal(DashoA13*..)
    at javax.crypto.Cipher.doFinal(DashoA13*..)
    at Securitytest.decrypt(Securitytest.java:208)
    at Securitytest.byteConvert(Securitytest.java:117)
    at Securitytest.main(Securitytest.java:265)
    the code i am using is the following. please help me i am going mad! the iv is the same for reading in and out and the secret key appears to be the same.
    import java.io.ByteArrayOutputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.PrintStream;
    import java.security.interfaces.RSAPrivateKey;
    import java.security.spec.PKCS8EncodedKeySpec;
    import java.security.spec.RSAPrivateKeySpec;
    import javax.imageio.stream.FileImageInputStream;
    import java.security.*;
    import java.io.*;
    import javax.crypto.*;
    import javax.crypto.spec.*;
    import sun.misc.*;
    import java.lang.*;
    public class Securitytest{
    public static void imageConvert( ) throws Exception {
    try{
    System.out.println("please select the file to encrypt");
    BufferedReader fileInput = new BufferedReader(new InputStreamReader(System.in));
    String filetoread = null;
    filetoread = fileInput.readLine();
    System.out.println("please select the file to save to");
    BufferedReader fileOutput = new BufferedReader(new InputStreamReader(System.in));
    String filetostore = null;
    filetostore = fileOutput.readLine();
    FileImageInputStream input = new FileImageInputStream(new File(filetoread));
    ByteArrayOutputStream output = new ByteArrayOutputStream();
    PrintStream stream = new PrintStream(output);
    byte[] buffer = new byte[1024];
    byte[] data = null;
    int numberBytesRead = 0;
    while ((numberBytesRead = input.read(buffer)) != -1)
    output.write(buffer, 0, numberBytesRead);
    data = output.toByteArray();
    System.out.println("encrytped" + buffer);
    System.out.println("going to encrypt");
    byte[] imageOutput = encrypt(data);
    System.out.println("back to imageconvert");
    System.out.println("encrytped" + buffer);
    FileOutputStream imageOut = new FileOutputStream(new File(filetostore));
    imageOut.write(imageOutput,0,imageOutput.length);
    imageOut.close();
    //BASE64Encoder encoder = new BASE64Encoder();
    //String enc = encoder.encodeBuffer(imageOutput);
    //FileWriter fw = new FileWriter(filetostore);
    FileOutputStream fos = new FileOutputStream(filetostore);
    fos.write(imageOutput);
    fos.close();
    System.out.println("sent to file");
    output.close();
    input.close();
    } catch(Exception ex) {
    System.out.println("Exception: " + ex);
    ex.printStackTrace();
    public static void byteConvert()throws Exception{
        try{
    System.out.println("please select the file to decrypt");
    BufferedReader fileInput = new BufferedReader(new InputStreamReader(System.in));
    String filetoread = null;
    filetoread = fileInput.readLine();
    System.out.println("please select the file to save to");
    BufferedReader fileOutput = new BufferedReader(new InputStreamReader(System.in));
    String filetostore = null;
    filetostore = fileOutput.readLine();
    FileInputStream fis = new FileInputStream(filetoread);
    byte[] decrypt = new byte[fis.available()];
    fis.read(decrypt);
    fis.close();
    //String dec = new String(decrypt);
    //BASE64Decoder decoder = new BASE64Decoder();
    //byte[] byteSeed = decoder.decodeBuffer(dec);
    // FileInputStream input = new FileInputStream(new File(filetoread));
    // ByteArrayOutputStream inStream = new ByteArrayOutputStream();
    // PrintStream stream = new PrintStream(inStream);
    // PrintStream stream = new PrintStream(input);
    // BASE64Decoder decoder = new BASE64Decoder();
    // String dec = decoder.decodeBuffer(stream);
    // String dec = new String(stream);
    // byte[] decryptionBytes = inStream;
    // byte[] s = decrypt(dec);
    // decryptionBytes =(byte [])stream.readStream();
    // stream.close();
    // for(int i=0; i < decryptionBytes.length; i++)
        // System.out.print(decryptionBytes);
    byte[] imageOutput = decrypt(decrypt);
    //byte[] imageOutput = decrypt(decrypt);
    FileOutputStream imageOut = new FileOutputStream(new File(filetostore));
    imageOut.write(imageOutput,0,imageOutput.length);
    imageOut.close();
        }catch(Exception ex) {
    System.out.println("Exception: " + ex);
    ex.printStackTrace();
    //new being used for AES
    public static byte[] encrypt(byte[] imageBytes) throws Exception {
    byte[] iv = new byte[] {(byte)0x2A, (byte)0x98, (byte)0xB2, (byte)0xBA, (byte)0x99, (byte)0xC0,
                (byte)0xF1, (byte)0x22, (byte)0x72, (byte)0x54, (byte)0xBC,
                (byte)0xB5, (byte)0x34, (byte)0x2F, (byte)0xBA, (byte)0xC4};
    byte[] encrypte = new byte[imageBytes.length];
    //System.out.println("Imagebyte length: " + imageBytes.length);
    System.out.println("in encrypt");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    SecretKey secretKeySpec = AESkeyGeneration();
    //IvParameterSpec ivSpec = new IvParameterSpec();
    //Cipher.getIV()
    System.out.println("read out" + secretKeySpec);
    //IvParameterSpec iv = new IvParameterSpec(IV_BYTE_ARRAY);
    cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec (iv));
    //byte[] encrypted = cipher.doFinal(imageBytes);
    FileOutputStream fos = new FileOutputStream("c:/text.txt");
    CipherOutputStream cOut = new CipherOutputStream(fos, cipher);
                // Your plaintext MUST be multiple of 16 bytes because NoPadding requires your input text
                // to be a multiple of block size.
    cOut.write(imageBytes);
    cOut.close();
    return cipher.doFinal(imageBytes);
    //return encrypted;
    public static byte[] decrypt(byte[] bytesIn) throws Exception{
    byte[] iv = new byte[] {(byte)0x2A, (byte)0x98, (byte)0xB2, (byte)0xBA, (byte)0x99, (byte)0xC0,
                (byte)0xF1, (byte)0x22, (byte)0x72, (byte)0x54, (byte)0xBC,
                (byte)0xB5, (byte)0x34, (byte)0x2F, (byte)0xBA, (byte)0xC4};
    System.out.println("in decrypt");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    System.out.println("cipher instance");
    SecretKey secretKeySpec = AESkeyGeneration();
    System.out.println("key" + secretKeySpec);
    System.out.println("keyRead in");
    //PrivateKey prvk = loadPrvkey();
    System.out.println("read out" + secretKeySpec);
    cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec (iv));
    System.out.println("Decrypt mode");
    return cipher.doFinal(bytesIn);
    //byte[] decodeData= cipher.doFinal(bytesIn);
    //return decodeData;
    private static SecretKeySpec AESkeyGeneration() {
    SecretKeySpec secretKeySpec = null;
    try {
    KeyGenerator kgen = KeyGenerator.getInstance("AES");
    kgen.init(128);
    SecretKey skey = kgen.generateKey();
    byte[] key = skey.getEncoded();
    secretKeySpec = new SecretKeySpec(key, "AES");
    FileOutputStream fosKey = new FileOutputStream ("c:/AES.key");
    fosKey.write (key);
    fosKey.close();
    }catch(Exception e) {
      System.out.println("error in keygen = "+e);
      return secretKeySpec;
    public static void main (String[] unused) throws Exception {
    System.out.println("***********************************************");
    System.out.println("***    Biometric Encrytion Program          ***");
    System.out.println("***********************************************");
    System.out.println("Please select a process");
    System.out.println("e for encryption ");
    System.out.println("d for decrytion");
    boolean choose = false;
    BufferedReader userInput = new BufferedReader(new InputStreamReader(System.in));
    String choice = null;
    choice = userInput.readLine();
    if (choose = choice.equals("e")){
    imageConvert();
    System.out.println("Encryption");
    else
    System.out.println("Decryption");
    byteConvert();
    }

    sorry i misinterepreted something. that program failured for some input only

  • Posiibility for terminating jvm inside try block so that finally block wont

    posiibility for terminating jvm inside try block so that finally block wont execute at all ?
    But in that case what will happen?
    Is it safe for any practical situation ?
    Threads: t.stop()
    JVM : System.exit()
    which one can really help and where?

    What if security Manager comes into picture?
    class ExitCatchingSecurityManager extends SecurityManager
    public void checkExit(int status)
    Process.terminateProcessWithThreadGroup(getThreadGroup());
    throw new SecurityException();
    What if an application calls System.exit()?
    We still have one big hole in our multiprocess library. If any application calls System.exit(), the JVM terminates, and all the pseudo-processes will be destroyed with no warning. Fortunately, Java's design once again comes to our aid. Any call to System.exit() is first checked by the SecurityManager to see if the application has permission to terminate the JVM. We can install our own SecurityManager to catch the System.exit() call, disallow it, and terminate the pseudo-process instead. The SecurityManager is actually quite simple to define:
    class ExitCatchingSecurityManager extends SecurityManager
    public void checkExit(int status)
    Process.terminateProcessWithThreadGroup(getThreadGroup());
    throw new SecurityException();
    In addition, the SecurityManager should define all other checks so that they do not block pseudo-processes from running. A simple null call for all check* methods will work. We install our own SecurityManager by calling System.setSecurityManager(), i.e., by adding the following line near the startup of the multiprocess library:
    System.setSecurityManager(new ExitCatchingSecurityManager());
    The Process.terminateProcessWithThreadGroup() method is simple to define, by holding a collection of Process objects in the Process class, searching the collection to find the Process with the identical ThreadGroup, then terminating that Process.

  • Why its not a good idea to have a return statement in a finally block?

    deepak

    Finally executes after the try block has finished doing its work--either successfully or not. Finally is only for cleanup that has to be run after try finishes, regardless of how try completes. It's up to the try block to handle the business logic, the real work.
    If the real work in the try block says, "return x," then it is not appropriate for finally--the cleanup code--to alter that with "return y" or "throw new Exception()".
    If the real work in the try block throws an exception, it is not appropritae for the cleanup code to throw a different exception, or change that to a return.
    Remember, if you throw or return from within finally, that will superceded whatever your mode of completion in the try block was.

  • Finally blocks for jdbs methods

    my code is filled with these jdbc methods that have a lot of try/catch blocks in which they either call private methods, or perform db queries.
    i was told that i may want to look into adding finally blocks to release database resources at the end of these types of methods. can anyone point me in the right direction re: what these proposed finally blocks should look like?
         * createAuction is used by user to add a new Auction
         * in the system.
         * @param newAuction AuctionEntryStruct containing data for new auction
         * @return int the new unique Auction ID
         * @exception com.kafein.idl.exceptions.DataValidationException
        public int createAuction(AuctionEntryStruct newAuction) throws
            DataValidationException {
             * Validate user (account and password), and then validate auction data.
             * Both methods throw DataValidationExceptions.
            validateAccount (newAuction.accountID, newAuction.userPassword);
            validateAuction (newAuction);
             * Generate new unique Auction ID, create Auction, and store in system.
            int auctionID = getNextID();     
            Auction anAuction = new Auction(auctionID,
            newAuction.accountID,
            newAuction.productName,
            newAuction.auctionCategory,
            newAuction.auctionDescription,
            newAuction.auctionStartingBid,
            newAuction.auctionBidIncrement,
            newAuction.auctionDuration);
            // Insert Auction into Database
            try {
                insertAuction(newAuction.accountID, anAuction);
            catch(Exception e) {
                e.printStackTrace();       
            auctions.put(auctionID,anAuction);
            return auctionID;
         * insertAuction is used to insert a new Auction in the Database
         * @param int AuctionID
         * @return AuctionStruct containing data for the existing Account
        private void insertAuction(int account_id, Auction anAuction) throws Exception {
            AuctionStruct anAuctionStruct = anAuction.getAuctionStruct();  
            int auction_id = anAuctionStruct.auctionID;
            int auction_acct_id = account_id;
            String  auction_productname    = anAuctionStruct.productName;
            String  auction_category = anAuctionStruct.auctionCategory;
            String  auction_description = anAuctionStruct.auctionDescription;
            float  auction_startingbid = anAuctionStruct.auctionStartingBid;
            float  auction_currentbid = anAuctionStruct.auctionCurrentBid;
            float  auction_maximumprice = anAuctionStruct.auctionMaximumPrice;
            float  auction_bidincrement = anAuctionStruct.auctionBidIncrement;
            int auction_numberofbids = anAuctionStruct.numberOfBids;
            try {
                System.out.println("Inserting data...");
                connection.setAutoCommit(false);
                // Calculate Start time
                Log.debug("Starting data insertion ( 1" +
                " row) into AUCTION table..");
                long startTime = System.currentTimeMillis();
                preparedStatement = connection.prepareStatement(
                "INSERT INTO AUCTION (AUCTION_ID, AUCTION_ACCT_ID, AUCTION_PRODUCTNAME, AUCTION_CATEGORY, AUCTION_DESCRIPTION, " +
                "AUCTION_STARTINGBID, AUCTION_CURRENTBID, AUCTION_MAXIMUMPRICE, AUCTION_BIDINCREMENT, AUCTION_NUMBEROFBIDS, LAST_UPDATE, AUCTION_STARTTIME, AUCTION_CLOSINGTIME) VALUES ( ?, ?, ?, ?, ?, ? , ?, ?, ?, ?,?,?,?)");
                auction_acct_id  = auction_acct_id;
                preparedStatement.setInt(1, auction_id);
                preparedStatement.setInt(2, auction_acct_id);
                preparedStatement.setString(3, auction_productname);
                preparedStatement.setString(4, auction_category);
                preparedStatement.setString(5, auction_description);
                preparedStatement.setFloat(6, auction_startingbid);
                preparedStatement.setFloat(7, auction_startingbid);
                preparedStatement.setFloat(8, auction_maximumprice);
                preparedStatement.setFloat(9, auction_bidincrement);
                preparedStatement.setInt(10, auction_numberofbids+1);
                //preparedStatement2.setInt(8, auction_duration);
                // use a SQL Timestamp to store a Time
                java.sql.Timestamp aTimestamp = new Timestamp(System.currentTimeMillis());
                preparedStatement.setTimestamp(11, aTimestamp);        
                // use a SQL Timestamp to store a date               
                Calendar aDate = ServiceHandler.decodeDateTime (anAuctionStruct.auctionStartTime);
                aTimestamp = new Timestamp(aDate.getTimeInMillis());
                preparedStatement.setTimestamp(12, aTimestamp);
                // use a SQL Timestamp to store a date               
                aDate = ServiceHandler.decodeDateTime (anAuctionStruct.auctionClosingTime);
                aTimestamp = new Timestamp(aDate.getTimeInMillis());
                preparedStatement.setTimestamp(13, aTimestamp);
                preparedStatement.executeUpdate();
                connection.commit();
                System.out.println("1 auction created.");
                preparedStatement.close();
                long stopTime = System.currentTimeMillis();
                Log.debug("Auction table load complete.");
                Log.debug("Load time = " +
                ((stopTime - startTime)/(1000f)) + " seconds");
                Log.debug("Data insertion complete");
            } catch(Exception e) {
                System.err.println("System Exception in loadData");
                System.err.println(e);
                throw e;
        }

    I guess there are two parts to the question:
    1) Why do you need to close these things?
    2) Why does said closing need to occur inside a finally block?
    1) Connections, etc. are finite resources. You need to give them back when you're done with them.
    You mentioned GC. GC is only relevant for memory. The VM can tell when you're done using a chunk of memory, and return that chunk to the pool of available memory. It does this without your help. GC does not apply to other resources--file handles, sockets, DB connections, etc. You need to explicitly release these when you're done with them. Must such resources do so via a close() call.
    Some people will try to use the finalize() method (also called a finalizer), which is completely different from the finally block, to clean up non-memory resources. This is not a good idea. Finalize is called as part of the GC process, whose job it is to make sure memory is available when it's needed, but those other resources are typically more scarce than memory, and become available and needed on a schedule that's largely independent of that of memory. Your code can run a long time without a GC, leaving a connection or socket that you're done with hanging around and unusable by other apps or other parts of your app.
    2) You do it in a finally block because no matter how the try and catch complete--as long as they do complete--the finally block will be executed. The term "complete" here has a fairly specific meaning in the JLS, but basically the only ways you could get finally not to run would be to call System.exit() or System.halt(), or to kill the VM by some other means.
    Even if you throw or return from within the try block or the catch block, the associated finally block, if present, will be executed. (Note, you don't even need a catch block--you can have just try and finally. try {
        if (something) {
            return; // finally will be executed before the method ends.
        else {
            throw new Exception();  // finally will be executed before the method ends
    finally {
        // cleanup
    }

  • BadPaddingException: Given final block not propertly padded -- Help Please

    I keep getting --Exception in thread "main" javax.crypto.BadPaddingException: Given final block not properly padded.       
    I know the problem lies with me writing to the encrypted text file or at some point when I'm actually reading it. Here's the code of these points......
    ciph.init(Cipher.ENCRYPT_MODE, skeySpec);
    /* The encryption begins */
    byte[] textBytesEncrypted = ciph.doFinal(textBytes);
    String bText = Base64.encodeBytes(textBytesEncrypted);
    // pw is a PrintWriter, I've also tried to use a FileOutputStream object
    // and write the entire byte array to a data file (without converting to
    // a String -- but that also resulted with the same exception being
    // thrown
    pw.write(bText);
    pw.close();
    public void decryptFile()
    throws IOException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
    IllegalBlockSizeException, BadPaddingException
    /* These lines will be writing and reading to the files */
    FileInputStream in = new FileInputStream(new File("C://outfile.txt"));
    PrintWriter pw = new PrintWriter(new File("C://outfile3.txt"));
    boolean done = false;
    int i = 0;
    ArrayList<Byte> bytearr = new ArrayList<Byte>();
    /* This loop places each of the bytes into an Array List, I'm using this because of the
    automatic resizing */
    while(!done)
    int next = in.read();
    if(next == -1) done = true;
    else{
    bytearr.add(i, (byte)next);
    i++;
    /* This variable retrieves the size of the array list in which the array will be set to */
    int length = bytearr.size();
    byte[] textBytes = new byte[length];
    /* This loop will move the Array List of bytes into the above array of bytes for future use */
    for(int j=0; j<length; j++)
    textBytes[j] = bytearr.get(j);
    ciph.init(Cipher.DECRYPT_MODE, skeySpec);
    /* The encryption begins */
    byte[] textBytesEncrypted = ciph.doFinal(textBytes);
    String text= new String(textBytesEncrypted);
    pw.write(text);
    in.close();
    pw.close();
    Any help would be greatly appreciated.

    You have not really supplied enough code to say exactly what is wrong BUT I would bet it is because you are treating files as containing chars and lines instead of just bytes.
    My suggestion - read the input files as bytes and encrypt/decrypt using CipherInputStream.

Maybe you are looking for

  • How can I check for references to previous server and remove them?

    I recently migrated several Win7 PC's off an old sbs2003 box to a new 2012 essentials server. All client data is stored on the server in a shared folder and that is mapped to the local PC's. Everything has been great, except we have noticed a delay o

  • Error While Filtering a Particular Value in the Query Navigation

    Hi ALL,         we have a time charecteristic 0FISCPER in our query and the output of the query  is fine until we filter this on the variant  V3 ,system is throwing an error   "System error in program SAPLRRK0 and form SORT_END_TRUE-01- (see long tex

  • UI (User Interface) text size and colors

    Recent versions of Elements (7, 8, 9) have changed to a user interface which is predominantly shades of gray and black with few if any user options for color or font. The font size cannot be altered because Adobe use their own pixel-based font which

  • Personal Data changes were not saved

    Hi, From the Personal Profile, I am able to edit and save data in all the sections but not for the Personal Data. Once after clicking on the Edit button from the Personal Data as shown below: We are getting below Edit Personal Data screen. Upon click

  • Satellite A200-1GB PSAE6 Flashcards issue - serial number is invalid

    Hi all. I need help and something for my headache... :D Today I were looking to the updates zone and see a newer version for the Flashcard, so I donwloaded it and install, but now begin the problems... when the setup starts it says that must uninstal