Catch SQLServerException

I know that a method can throw an non-runtime exception, so that a calling method can either throw or catch that exception. Right now, I am not so sure of what would happen if I write something that catch a runtime exception.
Here, I am using Eclipse 3.2 and Junit 3.8.1 to catch a particular exception called SQLServerException. The following code is shown as follows:
     public void testIncorrectInput() {
          try {
               Casefile d = Casefile.load("1");
               CaseComment.load(d, "w");
          } catch (SQLServerException e) {
               System.out.println("here");
The CaseComment.load() method does not explicilty throw SQLServerException but that is where the SQLServerException is coming from. According to the Microsoft Help document, the SQLServerException extends from java.sql.SQLException which also extends from Exception. I assume that I can catch any exception regardless of whether it is a runtime exception or not. The thing is that the Eclipse complained, "Unreachable catch block for SQLServerException. This exception is never thrown from the try
statement body."
Why is this happening? Is my assumption of catching any exception wrong?

I commented out the try and catch keywords and run the test. This is what I get:
com.microsoft.sqlserver.jdbc.SQLServerException: Conversion failed when converting the varchar value 'w' to data type smallint.
     at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDatabaseError(Unknown Source)
     at com.microsoft.sqlserver.jdbc.IOBuffer.processPackets(Unknown Source)
     at com.microsoft.sqlserver.jdbc.SQLServerStatement.buildNextRowset(Unknown Source)
     at com.microsoft.sqlserver.jdbc.SQLServerStatement.getNextResult(Unknown Source)
     at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.getPrepExecResponse(Unknown Source)
     at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.doExecutePreparedStatement(Unknown Source)
     at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement$PreparedStatementExecutionRequest.executeStatement(Unknown Source)
     at com.microsoft.sqlserver.jdbc.CancelableRequest.execute(Unknown Source)
     at com.microsoft.sqlserver.jdbc.SQLServerConnection.executeRequest(Unknown Source)
     at com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement.executeQuery(Unknown Source)
     at gov.ocda.cms2.core.CMSObject.loadDataSet(CMSObject.java:61)
     at gov.ocda.cms2.model.casefile.CaseComment.load(CaseComment.java:35)
     at junit.CaseCommentTest.testIncorrectInput(CaseCommentTest.java:37)
     at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
     at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
     at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
     at java.lang.reflect.Method.invoke(Unknown Source)
     at junit.framework.TestCase.runTest(TestCase.java:154)
     at junit.framework.TestCase.runBare(TestCase.java:127)
     at junit.framework.TestResult$1.protect(TestResult.java:106)
     at junit.framework.TestResult.runProtected(TestResult.java:124)
     at junit.framework.TestResult.run(TestResult.java:109)
     at junit.framework.TestCase.run(TestCase.java:118)
     at org.eclipse.jdt.internal.junit.runner.junit3.JUnit3TestReference.run(JUnit3TestReference.java:128)
     at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:460)
     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:673)
     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:386)
     at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:196)
I believe that whatever code inside the try clause did throw the exception. What does it mean?

Similar Messages

  • Com.microsoft.sqlserver.jdbc.SQLServerException The TCP/IP connection  fail

    * While executing the following JDBC code with SQLServer 2005, it throws Exception
    * I dont wts wrong in my code, (Note: I have included the sqljdbc.jar in my path)
    * Pls let me know the problems in my code
    * Thanks, Following is my code and error
    My Coding :
    import java.sql.*;
    public class JDBCwithJava {
         public void work() {
               // Create a variable for the connection string.
               String connectionUrl = "jdbc:sqlserver://localhost:1433;" +"databaseName=empdb";
               // Declare the JDBC objects.
               Connection con = null;
               Statement stmt = null;
               ResultSet rs = null;
               try {
                    //Load the driver
                  Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                  // Establish the connection.
                  con = DriverManager.getConnection(connectionUrl);
                  System.out.println("Database Successfully Connected...!");
                  //Connection Info
                  DatabaseMetaData dm = con.getMetaData();
                 System.out.println("Driver Information");
                 System.out.println("\t Driver Name: "+ dm.getDriverName());
                 System.out.println("\t Driver Version: "+ dm.getDriverVersion ());
                 System.out.println("\n Database Information ");
                 System.out.println("\t Database Name: "+ dm.getDatabaseProductName());
                 System.out.println("\t Database Version: "+ dm.getDatabaseProductVersion());
                  // Create and execute an SQL statement that returns some data.
                  String SQL = "select  * from emptable";
                  stmt = con.createStatement();
                  rs = stmt.executeQuery(SQL);
                  // Iterate through the data in the result set and display it.
                  while (rs.next()) {
                     System.out.println(rs.getInt(1) + " " + rs.getString(2));
               // Handle any errors that may have occurred.
               catch (Exception e) {
                  e.printStackTrace();
               finally {
                  if (rs != null)
                       try {
                            rs.close();
                      catch(Exception e) {
                  if (stmt != null) try { stmt.close(); } catch(Exception e) {}
                  if (con != null) try { con.close(); } catch(Exception e) {}
         public static void main(String ar[]){
              JDBCwithJava call = new JDBCwithJava();
              call.work();
    Error :
    com.microsoft.sqlserver.jdbc.SQLServerException: The TCP/IP connection to the host  has failed. java.net.ConnectException: Connection refused: connect
         at com.microsoft.sqlserver.jdbc.SQLServerException.makeFromDriverError(Unknown Source)
         at com.microsoft.sqlserver.jdbc.SQLServerConnection.connectHelper(Unknown Source)
         at com.microsoft.sqlserver.jdbc.SQLServerConnection.loginWithoutFailover(Unknown Source)
         at com.microsoft.sqlserver.jdbc.SQLServerConnection.connect(Unknown Source)
         at com.microsoft.sqlserver.jdbc.SQLServerDriver.connect(Unknown Source)
         at java.sql.DriverManager.getConnection(Unknown Source)
         at java.sql.DriverManager.getConnection(Unknown Source)
         at JDBCwithJava.work(JDBCwithJava.java:17)
         at JDBCwithJava.main(JDBCwithJava.java:58)

    Do you have SQL Server on your box? Is it listening on port 1433?
    I also don't see any username/password information provided to the JDBC driver.

  • Photoshope Elements when selecting an action, the paint brush tool doesn't work and system keeps freezing, then catching up every 30-45 seconds

    I have been having this problem with elements ever since the last OS upgrade, but it wasn't all the time and it wasn't very bad. Now, I have upgraded my macbook again, and I cannot even edit a photo!! I open the photo, choose an action, say "smooth skin", then choose the paint brush, I start to "paint" over their face and it won't paint a line, I have to keep clicking it, click - it paints, move brush, click again - it paints. Plus, every time I choose a tool or an action, it freezes for about 10 seconds, then catches up to what I am doing, 30 seconds later, it freezes again. HELP!! I have 8 sessions to finish editing by this weekend!! I just want to cry!!

    Try deleting the prefs and the saved application state:
    A Reminder for Mac Folks upgrading to Yosemite | Barbara's Sort-of-Tech Blog

  • Help to catch the output of a Transaction

    Hi,
    I have this issue and need help, I have a program lets say "ZPROGRAM", this programs calls a RFC "ZFUNC" this function must be able to send the parameters to execute a SAP standard transaction for example MB51, the function must send the plant number, storage location, and material number, then this RFC must catch the output of the report into an internal table so that i can work with the output in "ZPROGRAM", in other words what I see on screen as result of MB51 I need it in an internal table so that I can manupulate the data.
    I hope someone could tell me how to accomplish this.
    Thanks in advice.

    Hi,
       Pls try
        DATA list_tab TYPE TABLE OF abaplist.
        DATA vlist  LIKE  table of LISTZEILE WITH HEADER LINE.
        submit RM07DOCS
          with XXX
          EXPORTING LIST TO MEMORY
          and return .
          CALL FUNCTION 'LIST_FROM_MEMORY'
            TABLES
              listobject = list_tab
            EXCEPTIONS
              not_found  = 1
              OTHERS     = 2.
       CALL FUNCTION 'LIST_TO_ASCI'
          EXPORTING
            list_index         = -1
          TABLES
            listasci           = vlist
            listobject         =list_tab
          EXCEPTIONS
            empty_list         = 1
            list_index_invalid = 2
            OTHERS             = 3.
    Regards,
    Pole
    Edited by: Pole li on Jul 17, 2008 3:57 AM

  • How to catch error message inside a variable?

    Hi,
    I'm trying to catch the error message inside a variable using this this command below:-
    <%=odiRef.getPrevStepLog("MESSAGE")%>
    Could you please tell me what is the right approach to capture the error message inside a variable.
    Thanks
    Anindya

    Hi Bhabani,
    I have done this and select an oracle schema.But the variables only captures the (null).Please look into this.You must have one step prior to this refresh variable. Then only it can get the status as given below.
    Returns the one-letter code indicating the status with which the previous step terminated. The state R (Running) is never returned.
    D: Done (success)
    E: Error
    Q: Queued
    W: Waiting
    M: Warning
    If you want the complete error details then you will face issues in case of multi line message. For this best option would be jython variable.Could please provide me some idea how to use this jython variable.I will update you on this soon
    Thanks
    Anindya

  • How to catch exception into a String variable ?

    I have a code
    catch(Exception e)
                e.printStackTrace();
                logger.error("\n Exception in method Process"+e.getMessage());
            }when i open log i find
    Exception in method Process null.
    But i get a long error message in the server console !! I think thats coming from e.printStackTrace().
    can i get the error message from e.printStackTrace() into a String variable ?
    I want the first line of that big stacktrace in a String variable.
    How ?

    A trick is to issue e.printStackTrace() against a memory-based output object.
    void      printStackTrace(PrintStream s)
             // Prints this throwable and its backtrace to the specified print stream.
    void      printStackTrace(PrintWriter s)
    //          Prints this throwable and its backtrace to the specified print writer.Edited by: BIJ001 on Oct 5, 2007 8:54 AM

  • Facing problem while going to  catch return result from web-services.

    Hi everybody,
    I am new to BPEL. I am facing problem while going to catch the attributes of resultsets returning from web-services(QAS). As far as my knowledge, two types of results it should return - XML entities and another is attributes which is coming as the part of XML entitites. I am able to catch the XML entities, but can't catch the attributes under it. Even, I am not able to see whether web-services returning something within that field.
    When, I tried to catch the attribute and store to a temporary varilable using the following code:
    *<assign name="AssignQASDoGetAddress1">*
    *<copy>*
    *<from variable="InvokeQAS_DoSearch_OutputVariable"*
    part="body"
    query="/ns6:QASearchResult/ns6:QAPicklist/ns6:PicklistEntry/@PostcodeRecoded"/>
    *<to variable="temp"/>*
    *</copy>*
    *</assign>*
    but, I am facing the following selectionFailure errors after running it:
    *"{http://schemasxmlsoap.org/ws/2003/03/business-process/}selectionFailure" has been thrown.*
    -<selectionFailure xmlns="http://schemasxmlsoap.org/ws/2003/03/business-process/">
    -<part name="summary">
    *<summary>*
    empty variable/expression result.
    xpath variable/expression expression "bpws:getVariableData('InvokeQAS_DoSearch_OutputVariable', 'body', '/ns6:QASearchResult/ns6:QAPicklist/ns6:PicklistEntry/@PostcodeRecoded')" is empty at line 269, when attempting reading/copying it.
    Please make sure the variable/expression result "bpws:getVariableData('InvokeQAS_DoSearch_OutputVariable', 'body', '/ns6:QASearchResult/ns6:QAPicklist/ns6:PicklistEntry/@PostcodeRecoded')"is not empty.
    *</summary>*
    *</part>*
    *</selectionFailure>*
    Getting this error it seems to me that web-service is returning nothing, but, it returns something as it has been catched using a method called isPostcodeRecoded() Java Code in Oracle ADF. This method has been used as it should return boolean whereas for catching the xml entities using java code we used the method like getPostcode(), getMoniker().
    For your information, we are using Jdeveloper as the development tool for building the BPEL process.
    Am I doing any syntax error. Please consider it as urgent and provide me asolution.
    Thanks in advance.
    Chandrachur.

    Thanks Dave and Marc, for your suggestions. Actually what I found is QAS web-service is returning nothing as attributes when the attributes are set to the default value. For example, following is the part of the wsdl of the result which QAS webservice returns.
    <xs:element name="QASearchResult">
    - <xs:complexType>
    - <xs:sequence>
    <xs:element name="QAPicklist" type="qas:QAPicklistType" minOccurs="0" />
    <xs:element name="QAAddress" type="qas:QAAddressType" minOccurs="0" />
    </xs:sequence>
    <xs:attribute name="VerifyLevel" type="qas:VerifyLevelType" default="None" />
    </xs:complexType>
    </xs:element>
    <xs:complexType name="QAPicklistType">
    - <xs:sequence>
    <xs:element name="FullPicklistMoniker" type="xs:string" />
    <xs:element name="PicklistEntry" type="qas:PicklistEntryType" minOccurs="0" maxOccurs="unbounded" />
    <xs:element name="Prompt" type="xs:string" />
    <xs:element name="Total" type="xs:nonNegativeInteger" />
    </xs:sequence>
    <xs:attribute name="AutoFormatSafe" type="xs:boolean" default="false" />
    <xs:attribute name="AutoFormatPastClose" type="xs:boolean" default="false" />
    <xs:attribute name="AutoStepinSafe" type="xs:boolean" default="false" />
    <xs:attribute name="AutoStepinPastClose" type="xs:boolean" default="false" />
    <xs:attribute name="LargePotential" type="xs:boolean" default="false" />
    <xs:attribute name="MaxMatches" type="xs:boolean" default="false" />
    <xs:attribute name="MoreOtherMatches" type="xs:boolean" default="false" />
    <xs:attribute name="OverThreshold" type="xs:boolean" default="false" />
    <xs:attribute name="Timeout" type="xs:boolean" default="false" />
    </xs:complexType>
    <xs:complexType name="PicklistEntryType">
    - <xs:sequence>
    <xs:element name="Moniker" type="xs:string" />
    <xs:element name="PartialAddress" type="xs:string" />
    <xs:element name="Picklist" type="xs:string" />
    <xs:element name="Postcode" type="xs:string" />
    <xs:element name="Score" type="xs:nonNegativeInteger" />
    </xs:sequence>
    <xs:attribute name="FullAddress" type="xs:boolean" default="false" />
    <xs:attribute name="Multiples" type="xs:boolean" default="false" />
    <xs:attribute name="CanStep" type="xs:boolean" default="false" />
    <xs:attribute name="AliasMatch" type="xs:boolean" default="false" />
    <xs:attribute name="PostcodeRecoded" type="xs:boolean" default="false" />
    <xs:attribute name="CrossBorderMatch" type="xs:boolean" default="false" />
    <xs:attribute name="DummyPOBox" type="xs:boolean" default="false" />
    <xs:attribute name="Name" type="xs:boolean" default="false" />
    <xs:attribute name="Information" type="xs:boolean" default="false" />
    <xs:attribute name="WarnInformation" type="xs:boolean" default="false" />
    <xs:attribute name="IncompleteAddr" type="xs:boolean" default="false" />
    <xs:attribute name="UnresolvableRange" type="xs:boolean" default="false" />
    <xs:attribute name="PhantomPrimaryPoint" type="xs:boolean" default="false" />
    </xs:complexType>
    here the attributes like FullAddress, PostcodeRecodedare , etc. are not being return by the web-service when it is getting the default value false. But, if it gets true then , it is being displayed at the BPEL console.
    Do you have any idea how can I catch the attributes and its value even when it gets the default value which is already set. Previously, it was returning(it was not being displayed at the console).
    Thanks once again for your valuable suggestions...!!!
    Chandrachur.

  • Catch datetime exception and custom error message in SSRS

    I currently working on create report by using SSRS. I have 2 parameters: [Start date] and [End date] to filter data from database and show it on report. I want to validate 2 datetime parameter as describe above. Please tell me a solution to do this.
    For example:
    When user type the text like: 4/15/2014mmm => System validation thrown a message: [The From Date not correct type]
    But in my case, I want to receive a custom error message by myself.(Look like: [Date Invalid!])

    Hi Brain,
    According to your description, you have a report with two parameters for user to input. Now you want to validate these two parameters and display custom error message when the date is invalid. Right?
    In Reporting Service, it doesn’t provide any interference for us to modify the system error message (the text in grey color). That means we can’t modify the system message when error occurs. However we can create a textbox in this report, use custom code
    and expression to display the custom error message. But this all based on the report is successfully running. So if error occurs during report processing, all the custom code and expression will not work. In this scenario, we find a workaround for you. We
    use custom code to judge if the date is valid, if the users type an invalid date, we return a default value to make sure this report can successfully run. Then we use expression to control the visibility of tablix in this report and create a textbox to show
    the custom error message. Your case has been tested in our local environment. Here are steps and screenshots for your reference:
    Go to Report Properties. Put the code below into custom code:
    Public Shared a As Integer=0
    Public Shared Function IsDate(d1 As String,d2 As String) as Integer
            Try
               FormatDateTime(d1)
               FormatDateTime(d2)
            Catch ex As Exception
                       a=1
            End Try
    return a
    End Function
    Create two parameters. One is StartDate, the other is EndDate. Set the data type of these two parameters Text.
    Create a filter for StartDate, put the expression below into Value:
    =IIF(Code.IsDate(Parameters!StartDate.Value,Parameters!EndDate.Value)=0,CDate(IIF(Code.IsDate(Parameters!StartDate.Value,Parameters!EndDate.Value)=0,Parameters!StartDate.Value,"1/1/2012")),CDate("1/1/2012"))
    Create a filter for EndDate, put the expression below into Value:
    =IIF(Code.IsDate(Parameters!StartDate.Value,Parameters!EndDate.Value)=0,CDate(IIF(Code.IsDate(Parameters!StartDate.Value,Parameters!EndDate.Value)=0,Parameters!EndDate.Value,"1/1/2013")),CDate("1/1/2013"))
    Ps: In step3 and step4, the date(“1/1/2012”, “1/1/2013”) in the expression are the default we set to make sure the report can successfully process. You can set any date existing in your dataset.
    Use the expression below to set the visibility of the tablix:
    =IIF(Code.IsDate(Parameters!StartDate.Value,Parameters!EndDate.Value)=0,false,true)
    Create a textbox, put the expression below into it:
    =IIF(Code.IsDate(Parameters!StartDate.Value,Parameters!EndDate.Value)=0,"","Date invalid")
    Save and preview. It looks like below:
    Reference:
    SSRS Calendar and Date Restriction
    Errors and Events Reference (Reporting Services)
    If you have any question, please feel free to ask.
    Best Regards,
    Simon Hou
      

  • How to catch up Exception message?

    i have a question while using try{ ... }catch{ ... } clauses. for when update, delete, databse, there might be error occurred. all to often i do not deal with the message, only if to check log when serious problem i have to find it out; but i hope to learn how if i am able to display message of my own while erro occurrs. for instance, when falling into SQLException, originaly i might just utilize
    }catch(SQLException e){
    e.printStackTrace();
    is it possible for me to catch up message inside the printStackTrace that may happen while errors appearing? (or only down to catch{} clause be the last deadline that i am able to use? because i hope i am able to capture error code like ora-1234 and tranlate it into messages that user, who doesn't know too much about pc, can understand easily while reporting bug; and not just saying "we have problem here!")
    that is, if 'A' situation popping out, i hope to direct it to error page with special message shown. so does the same error page with different message specified while 'B' situation found out!
    any suggestions would be appreciated~
    thanks in advice,

    printStackTrace isn't obligatory. It's basically what you do with an exception when you don't have anything more specific to do with it.
    You can certainly catch a specific exception at any level, including inside another try {} block.
    Even having caught an exception you can decide that you don't want to handle it at this point in the code, and throw it again.
    You might do:
    try {
         try {
           ... statment which migh cause a particular database exception
            } catch(SQLException e) {
            if(e.getMessage().startsWith("ORA-1232")) {
              .. do somthing usefull
             } else
            throw e;   // the particular SQL exception was unexpected so go on and crash
       catch(Exception e) {
         e.printStackTrace();   // unexpected program failure

  • How to catch SAP application errors in BPM.

    Hi,
    I have a IDOC to Soap Sync Scenario where I send the message to a Webservice. I have used a BPM since we need to catch the resposne of this message and map it to a RFC. For ex if I get a success resposne I need to map success if not than I need to catch the error and map it to the RFC. Now here in some cases like if the target system (webservice) is down than XI raises a sap application error:
    <?xml version="1.0" encoding="UTF-8" standalone="yes" ?>
    - <!--  Inbound Message
      -->
    - <SAP:Error xmlns:SAP="http://sap.com/xi/XI/Message/30" xmlns:SOAP="http://schemas.xmlsoap.org/soap/envelope/" SOAP:mustUnderstand="1">
      <SAP:Category>XIAdapterFramework</SAP:Category>
      <SAP:Code area="MESSAGE">GENERAL</SAP:Code>
      <SAP:P1 />
      <SAP:P2 />
      <SAP:P3 />
      <SAP:P4 />
      <SAP:AdditionalText>com.sap.aii.af.ra.ms.api.DeliveryException: Connection refused (errno:239)</SAP:AdditionalText>
      <SAP:ApplicationFaultMessage namespace="" />
      <SAP:Stack />
      <SAP:Retry>M</SAP:Retry>
      </SAP:Error>
    Normally XI stops the process in these cases and does not proceed to the next step but I need to catch this message and map the content in the AdditionalText to the target RFC. Can anyone let me know how to catch this SAP Application Error in BPM and map it to the RFC.
    Thanks,
    Bhargav

    Hi Gaurav,
    As I have mentioned I need to catch the application error in the BPM. If you see the discussion that is mentioned after the blog you have mentioned it is stated that the fault messages or the application error cannot be caught in BPM.
    In the blog that you stated we can catch the fault message and map it to a message structure but only to that extent after that it would stop the BPM process at that step but would not proceed further as shown in the screenshot given in the blog it would fail as "application error restart not possible".
    I need to proceed further and capture this error to an RFC Structure and call a proxy.
    Here after the error it does not proceed to the next step.
    Thanks,
    Bhargav

  • How do we catch errors in Servlets?

    Hello, i 'm using Servlets and JDBC.
    i'm having a form.html where the user inserts data in the input fields.
    It's a registration page.
    I would like to check for possible user errors.
    For example if the user has not typed anything in a required field like field "password", so the field is null.
    I would like to inform the user that this field is null and he/she shall type in it again.
    (I'm talking generally not only for a registration page but to any page that requires correct data)
    *1.* Shall i use Javascript?
    *2.* Shall i direct the user to an error page where the page describes the error, what the user has to do in order to correct it and direct him back to the previous page?
    *3.* Shall i only use if/else?
    I would appreciate if sm could give me some advice on this matter or post me some links related to catch errors in servlets.
    Thanks, in advance!
    Edited by: g_p_java on Jul 11, 2009 12:15 PM

    Here is a possible approach to this issue:
    * use javascript to validate all textfields on the form client-side every time the user clicks the submit button. If it fails, put a message in red next to the problem textfield describing what the problem is. Dont allow submit if there are validation issues.
    * More than one validation may apply to a given textfield. For instance, the field cant be empty is checked before its checked for an invalid date.
    * Check to see if its an invalid date format first (example: mm/dd/yyyy), then check to see if its an invalid date (non leap year for example).
    * recheck all validation back on the server (necessary if user disabled javascript or a hacker bypasses your client side validation). Redraw the page and populate it, but put messages next to the problem fields as you did for javascript.
    * The invalid date format and invalid date should pass if given an empty value since the its the empty value validation (if it applicable for that field) that is repsonsible for that test.
    *since you will be applying this validation over and over again for all your JSP pages for this project and future projects, it may be a good idea to create reusable code for it. You may also research google for good approaches.
    Your javascript code should be from a single javascript file that is included into each JSP page so it can be reused.
    @see http://www.xs4all.nl/~sbpoley/webmatters/formval.html
    * All textfields should be validated throughly so your database never gets bad data (data is king).
    * common things to check for:
    invalid date format, invalid date, empty textfield, invalid email address, invalid telephone number format, invalid zip code, etc, etc, etc

  • Code in main does not require catch, but code in constructor does

    this is the original program, its all in main. i took all the code out of main and put it in a constructor to make it more usable, and started making the necessary adjustments. i eventually got it to work but i had to catch exceptions EVERYWHERE. why does this code not require so many exceptions when the code is in main?
    import java.io.BufferedInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLConnection;
    public class MainClass {
      public static void main(String args[]) throws Exception {
        URL u = new URL("");
        URLConnection uc = u.openConnection();
        String contentType = uc.getContentType();
        int contentLength = uc.getContentLength();
         // ||
        if (contentLength == -1) {
          throw new IOException("Error: No File Found.");
        InputStream raw = uc.getInputStream();
        InputStream in = new BufferedInputStream(raw);
        byte[] data = new byte[contentLength];
        int bytesRead = 0;
        int offset = 0;
        while (offset < contentLength) {
          bytesRead = in.read(data, offset, data.length - offset);
          if (bytesRead == -1)
            break;
          offset += bytesRead;
        in.close();
        if (offset != contentLength) {
          throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
         String dirText = "text";
         String dirTarget = "target";
         String filename = u.getFile().substring(u.getFile().lastIndexOf('/') + 1);
         String dirAndFile;
         // determine weather the file is a target or is to be parsed for more files
         if(contentType.startsWith("text/")) {
              dirAndFile = dirText + "\\" + filename;
         else {
              dirAndFile = dirTarget + "\\" + filename;
        FileOutputStream out = new FileOutputStream(dirAndFile);
        out.write(data);
        out.flush();
        out.close();
    }Edited by: chopficaro on May 1, 2010 8:15 AM

    ok but still, why do i not have to catch all these exceptions when the code is in main rather than a constructor? heres the code after i put it in the constructor:
    import java.io.BufferedInputStream;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.URL;
    import java.net.URLConnection;
    import java.net.MalformedURLException;
    public class MainClass {
         public static void main(String args[]) throws Exception
              MainClass mc = new MainClass("http://www.google.com/intl/en_ALL/images/logo.gif");
         MainClass(String addr)
              URL u = null;
              try
                   u = new URL(addr);
              catch (MalformedURLException e)
                   // Print out the exception that occurred
                   System.out.println("Invalid URL "+addr+": "+e.getMessage());
              URLConnection uc = null;
              try
                   uc = u.openConnection();
              catch (IOException e)
                   // Print out the exception that occurred
                   System.out.println("Unable to create "+addr+": "+e.getMessage());
              String contentType = uc.getContentType();
              int contentLength = uc.getContentLength();
              if (contentLength == -1)
                   System.out.println("no file");//throw new IOException("Error: No File Found.");
              InputStream raw=null;
              InputStream in=null;
              try
                   raw = uc.getInputStream();
                   in = new BufferedInputStream(raw);
              catch (IOException e)
              // Print out the exception that occurred
              System.out.println("bad input stream "+e.getMessage());
              byte[] data = new byte[contentLength];
              int bytesRead = 0;
              int offset = 0;
              while (offset < contentLength)
                   try
                        bytesRead = in.read(data, offset, data.length - offset);
                   catch (IOException e)
                        // Print out the exception that occurred
                        System.out.println(e.getMessage());
                   if (bytesRead == -1)
                   break;
                   offset += bytesRead;
              try
                   in.close();
              catch (IOException e)
                   // Print out the exception that occurred
                   System.out.println(e.getMessage());
              if (offset != contentLength)
                   System.out.println("didnt read enough bytes"); //throw new IOException("Only read " + offset + " bytes; Expected " + contentLength + " bytes");
              String dirText = "text";
              String dirTarget = "target";
              try
                   String filename = u.getFile().substring(u.getFile().lastIndexOf('/') + 1);
                   String dirAndFile;
                   // determine weather the file is a target or is to be parsed for more files
                   if(contentType.startsWith("text/"))
                        dirAndFile = dirText + "\\" + filename;
                   else
                        dirAndFile = dirTarget + "\\" + filename;
                   FileOutputStream out = new FileOutputStream(dirAndFile);
                   out.write(data);
                   out.flush();
                   out.close();
              catch (IOException e)
                   // Print out the exception that occurred
                   System.out.println(e.getMessage());
    }

  • Help me catch my hacker...please!

    Hi. I have an old Mac Pro 1,1 (2007 I believe), OSX 10.7.5 that has been hacked. I have read some of the questions here so I'll try to include all the necessary info. some of the things that have happened are that a new admin user account is on my computer where I have never created any other account and was using my admin account solely which I now know is not smart. I see the new account at the login screen although it tries to look like it is my account, same icon, but it thankfully can't shut down or restart the computer. I am the sole user of my computer and no one else has access to it physically. also, I can no longer throw anything into the trash. Everything just gets moved somewhere as I can see this from the dialog box that pops up. Also, I have to enter a password just to throw anything away(!), but the trash bin always remains empty so nothing ever makes it there but is obviously going elsewhere. The other thing is all my files are now locked and password protected which of course I didn't do. So, hopefully this all shows my computer has indeed been hacked. In fact, I do know who has done this and he's hacked my iphone as well. He currently lives in another country and when I did wipe my phone and enable location services I started getting ads for the nearest major city of that country where he lives and he is the only person I know who lives in that country. I have other info too as to how I know who it is but won't go into it here. He is some guy I used to know who somehow thinks I'm responsible for him losing his job which is completely preposterous. I know he's gone after my finances but thus far has not been able to access them. My email, which I never check on my home computer or phone anymore, will even on my home computer keep trying to connect to paypal. When I've logged into AppleID on my phone to download apps he has changed my AppleID password & security questions but I was fortunately able to change it and get back into it. He put security questions I would never use like asking something about dates and I never remember dates.
    Anyway, I really need to catch this guy as I have info that he has done this to others as well. I know I could just wipe my machine but that is not something I want to do. While my mac tech guy is normally great he doesn't even believe a mac can have a virus and wants to debate that so for him to believe my computer could have been hacked is impossible so he wouldn't help me. I have contacted a couple other techs I know but one was PC-oriented and the other who does some work on macs said he didn't have enough mac experience when I told him the litany of things happening on my computer and phone. So, I am turning to the good people of this forum to help me do this myself as I know you guys are great from past experience with minor computer issues.
    What I've done so far, mostly from reading these forums: I ran EtreCheck and the only thing that came up looking off was a version of Adobe Flash Player I downloaded that EtreCheck says was a mismatch in their red type. I believe that is how the hacker got his software on my computer. I made visible all the users/accounts and nothing looked funny but a lot of this stuff is greek to me as I have never used the Terminal before. I did find a root user and so disabled that. I have looked through all the Processes, and ran that 5-step terminal thing you guys recommend here that shows preferences & launch agents, etc. and looked and looked but see nothing off. I unfortunately had my computer rather wide open before and so now have done all the normal user things to tighten my security and have Little Snitch and Avast Security on my computer. Oh, I did find the Genio-L bug through MacScan and deleted that. My computer had been running at a crawl but is now faster. Also, I had read something about hackers getting access through Bluetooth and saw besides my keyboard and mouse (my modem is wired so I don't have WiFi) some third item listed. I deleted it as it looked suspicious with very little info on it compared to my other devices. (I forgot to take a screenshot of it.) I have also made all files visible through the Terminal. I was looking around in the Private/Etc files but I don't really know what i'm looking at. Also, I found 3 applications that were loading automatically on login so I deleted them: Adobe Resource Synchronizer, Optimism Agent (Optimism software I have) and FontExplorer.
    Anyway, I would love recommendations for how to find this hacking software which I'm assuming can be found through the Terminal. I did try to use Deeper but when I tried to get it to show all the IP addresses for the users on the login page it had an applescript error come up. It said:
    FSPathMakeRef (/System/Library/CoreServices/HelpViewer.app) failed with error -43. (1)
    i'm sure this guy probably has some pretty sophisticated hacking software, which I understand can even be parental control software. I have reason to believe he has put a keylogger on my computer. So, if there is a way to catch this guy please, please give me some tips but do explain everything really simply & step by step as I know nothing about using the Terminal despite the few things I've done. I was reading under the ssh and it says something about -x being used to disable keyloggers from forwarding info. I do seem to have the applicaton X11 on my computer which I never noticed before. There was also something under ssh about ~# which can list all forwarded connections. Of course I don't know how or where to do these things but if you guys think it would help then I'd totally appreciate directions on how to do these things.
    Sorry for writing an essay but I may not be able to get back to this computer for 3-4 days so wanted to give plenty of info for the questions you guys usually ask. Thanks in advance for any and all help!

    I went ahead and repaired the permissions and the disk itself didn't need any repairs. I still really don't want to wipe my HD, and haven't yet, because I want to catch this guy. can you guys give me a code to enter into the Terminal to show all hidden admin users? I tried something I found on these forums to unhide all 500users but i'm not sure if it was for Lion. (btw, the descriptions for this forum are off. i have a silver tower, it's definitely a mac pro 1,1 and am running Lion 10.7.5) anyway, the terminal said in response:
    sudo: /private/etc/sudoers is mode 0446, should be 0440.
    this response was before I repaired the permissions.
    to address Kurt's question of why i'm convinced I have a hacker I didn't share everything in my OP partly because it was already so long and party because some info I don't feel comfortable sharing online. suffice it to say I have solid knowledge that I've been hacked. I was 99.9% sure of who it was and when the location-based ad on my iphone came up for the country this person currently lives in I knew I was right. think of it like this, if you knew one person who lived in Latvia and suspected he was for sure the person who hacked your computer/phone because you know he's done it to others you know, and suddenly your phone in the US starts getting ads for the nearest major city to where the person lives in Latvia, right after you enabled location-based ads, you'd be pretty sure you suspect the right person. as to how I know this is for sure a hacking I am not comfortable going into on a public forum. suffice it to say, I know without a shadow of a doubt. obviously, the fact that I have an additional admin account on my computer when I live alone and no one, and I mean no one, has physical access to my computer is quite a good indicator.
    just earlier today I had additional problems on my iphone 4. (in the last week I've reset the settings several times whenever I have like one or two bars for my connection which is definitely not normal. resetting the settings seems to be really helping the connection.) this morning I was reading on safari (on the NPR site) and suddenly my phone goes black and the same screen I see when my phone is resetting shows up (all-black screen with white horizontal progress bar). something was being reset so I immediately tried to turn off the phone and it wouldn't turn off, but it did not let the progress bar continue with whatever was happening as long as I held the power button down. then after awhile of doing this, the screen suddenly went back to my usual NPR page. I immediately turned off my phone and will reset it when I turn it back on.
    so, my question is how protect my phone? I have erased it previously, but don't want to do that again as I can't risk logging into Apple ID on it again, to download apps, as last time I did that my Apple ID password & security question as got changed and I had a hard time getting back into it. what I have done so far is to use a password, set a restrictions password and I have turned off most locations settings and limited ad tracking. when this all started awhile ago the app I use the most, a newspaper, suddenly popped up with a survey that it tried to force me to click on and take. there was no option not to take the survey and the website address it showed ended in .xyz as if that is a real legitimate site. what I did was close the app and delete it as I knew this had nothing to do with this major newspaper app. it was directly after that that the location-based ad in this guy's country started coming up. so, how the heck can I keep this guy off my phone now? I still want to catch him and am hoping I can somehow do that either on my computer or phone. no one should be allowed to do this to another person. it's been a nightmare. again thanks for any and all help.

  • How to catch accounting Document Number in SE37 for  BAPI_ACC_DOCUMENT_POST

    HI Frds,
    My ReQ is i have to post Customer Invoice from Legacy to ECC through PI interface. So i am using one BAPI , ' BAPI_ACC_DOCUMENT_POST''. I had customized this BAPI by adding 2 fields (1.zstatus, 2.zsaprefno) as i have to send the status(1. Success/Fail, 2.Account Document Number) back to Legacy.
    For PI i have to give the BAPI structure. So when i am executing in SE37 zstatus field is catching the value as 'Success'. But the ZSAPREFNO is not catching the account document number. Bez we have to execute BAPI_TRANSACTION_COMMIT after this BAPI(in test sequence from Menu bar). So directly updating in Database tables.
    when i was excuting in SE38 the Accounting Document Number is returned in RETURN parameter of MESSAGE_V2 as we are checking the return parameter after BAPI_TRANSACTION_COMMIT.
    when i am trying in SE37 its not catching the value in MESSAGE_V2(catching as $).  After COMMITing we have no option to check the RETURN parameter.
    So, any idea how to get the Account Document Number  in SE37.......Or any other way to do..........
    Edited by: priya tavanam on Sep 3, 2010 7:02 AM

    Hi,
    if standard BAPI did not return the Acc. document number before BAPI_COMMIT then create wrapper FM
    1) call actual BAPI and BAPI_COMMIT with in that.
    2) retrun the account document back.
    otherwise you can try sync proxy as well.
    Regds,
    Suresh

  • How to catch excpetions of function module?

    Hallo everybody,
    how can i catch the exception from function module "exception" and deliver it to call function parameter table --exception table.
    For example,a function module 'RPY_TABLE_INSERT' is called by Call Function (parameter_table)in order to create a new table.When the table exists already, a exception "Already_exist" activated.But it can not be caught,since it is raised by "message raise". Therefore in the exception-table of caller no error is caught.
    How can I deal with it?
    Thanks in advance!
    Message was edited by: Liying Wang

    CALL FUNCTION 'RPY_TABLE_INSERT'
      EXPORTING
      LANGUAGE                = SY-LANGU
        TABLE_NAME              =
      WITH_DOCU               = ' '
      DOCUTYPE                = 'T'
      TRANSPORT_NUMBER        = ' '
      DEVELOPMENT_CLASS       = '$TMP'
        TABL_INF                =
      TABL_TECHNICS           = ' '
      TABLES
        TABL_FIELDS             =
      DOCU_TABLE_USER         =
      DOCU_TABLE_TECH         =
    EXCEPTIONS
      CANCELLED               = 1
      ALREADY_EXIST           = 2
      PERMISSION_ERROR        = 3
      NAME_NOT_ALLOWED        = 4
      NAME_CONFLICT           = 5
      DB_ACCESS_ERROR         = 6
      OTHERS                  = 7
    IF SY-SUBRC <> 0.
      as per the error sy-subrc will be set, you can see in the exceptions ( 1 for cancel, 2 for already exit)
    so using this subrc you can determine the error
    ENDIF.

Maybe you are looking for

  • Query too slow on dictionary objects

    We need to optimize a query for a view running on 10.2.0.4 that is used when application code checks database privileges. This query takes about 4 or 5 seconds and we would like to have about 1 second. Thanks. Here is the view definition and some que

  • How to include Chart in Web Page not as seperate image file?

    Hi, I am using JCharts and am trying to figure out how (or if it is even possible) to create a chart and then place it in a web page. All the examples I've seen show you how to create a JPEG of the chart and then link to this image from your web page

  • InDesign cross-document Text Anchor Hyperlinks

    I'm combining several InDesign files into one PDF, with several hundred text links across the different sections, as well as within each. The cross-document (section) Text Anchor Hyperlinks work fine in my workspace - but when I change the file locat

  • TS3694 error message 2324 on update in iTunes - what does it mean?

    Every time I try to update my iTunes software on my Windows 7 PC it wont complete and throws up the error code 2324. I have no idea what it means ro how to resolve - any clues?

  • Function 'SO_DOCUMENT_SEND_API1' in BADI

    I am encountering difficulty using the function module  'SO_DOCUMENT_SEND_API1'  in a BADI; when the BADI executes the mail is partially created (new entries exits in table SOOD) it is however not sent nor is it viewable in BWP. Executing the same co