Handling exceptions

Hi all,
i have this slight problem, i'm trying to handle accessing a databse from a button click, i'm trying to simulate somebody logging on to a network. the code is as follows;
*@author James Taylor
*@version 30-11-2003
*Logon gui
import java.awt.*;
import javax.swing.*;
import java.awt.event.*;
import java.sql.*;
public class LogonUI extends JFrame {
     //instance variables
     private JLabel userNameL;
     private JPasswordField password;
     private JButton logon;
     ButtonHandler handler;
     Connection con;
     Statement stmt;
      *Constructor initialises and creates UI, adds functionality to the button.
     public LogonUI() throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException{
          super("Employee Logon");
          Container c = getContentPane();
          c.setLayout(new FlowLayout() );
          //handles what happens when user presses the button
           handler = new ButtonHandler();
          userNameL = new JLabel("Please Enter Password:");
          c.add(userNameL);
          password = new JPasswordField(15);
          c.add(password);
          logon = new JButton( "Logon" );
          //anonymous inner class that is created once the button is pressed.
          //it connects to database to validate user
          logon.addActionListener( handler );
          c.add(logon);
          c.setBackground( Color.pink );
          setDefaultCloseOperation(DISPOSE_ON_CLOSE);
          setSize(250,150);
          setVisible(true);
      *class that opens connection to validate user
     private class ButtonHandler implements ActionListener {
          public void actionPerformed(ActionEvent ae)throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException{
               try{
                    boolean isValidUser = false;
                    //Load mysql driver
                     Class.forName("com.mysql.jdbc.Driver").newInstance();
                     //make a connection
                    String url = "jdbc:mysql://localhost/flight";
                    con = DriverManager.getConnection(url)
                    //Create and instantiate a statement obj
                    stmt = con.createStatement();
                    //get a result set
                    ResultSet rs = stmt.executeQuery("SELECT Password FROM employees");
                    //Iterate through the result set
                    while ( rs.next() ){     
                         String savedPassword = rs.getString("Password");
                         if (password.getText().equals(savedPassword) ){
                              isValidUser = true;
                              JOptionPane.showMessageDialog(null,"Yipeeeee");
                    if (isValidUser == false){
                         JOptionPane.showMessageDialog(null,"Invalid Password");     
                    stmt.close();
                    con.close();
               }catch(Exception e){ e.printStackTrace();}
          public static void main (String[] args) throws SQLException, ClassNotFoundException, IllegalAccessException, InstantiationException{
          LogonUI testAirApp = new LogonUI();
}When the user presses the button the app tries to validate the user.
I have not been able to test the code due to SQL Exceptions thrown in the handler class, and when i try and throw them up from here i get;
LogonUI.java:52: actionPerformed(java.awt.event.ActionEvent) in LogonUI.ButtonHandler cannot implement actionPerformed(java.awt.event.ActionEvent) in java.awt.event.ActionListener; overridden method does not throw java.lang.InstantiationExceptionAny ideas on my code and how to handle these exceptions will be very appreciated. Regards, James

More your public void actionPerformed(ActionEvent ae) does not throw SQLException, ClassNotFoundException and IllegalAccessException.
You catches exceptions in method code.
Remove any exceptions from method declaration

Similar Messages

  • Invalid Handle Exception-What is the reason?

    I face with "Invalid Handle exception" (SQLException) while using the following code.
    Could anybody tell me the possible reasons/Situation the error rise?
    stmt = conn.createStatement();
    ResultSet rs = stmt.executeQuery(SQLStmt);
         if(rs!=null){
    ResultSetMetaData rsm = rs.getMetaData();
         int totalcols = rsm.getColumnCount();
         Vector temp;
         while (rs.next()) {
         Vector temp = new Vector();
         for (int i = 1; i <= totalcols; i++) {
              String value = rs.getString(i);
              if (value == null) {
              value = "";
         temp.addElement(value);
         }//for loop ends here
         valueVector.addElement(temp);
         rs.close();
         stmt.close();     
    Thank you all

    Vector temp;
    while (rs.next()) {
    Vector temp = new Vector();Are you sure that this is the code you are running? The reason I ask is that I'm pretty sure that it won't compile, at least under JDK1.4. You should get a compile error something like "temp is already defined".
    If thats not the problem you need to find out on which line the error actually occurs. You can get this from the exception by calling the printStackTrace() method.
    Col

  • Can we handle exceptions for the expressions in select query?

    Hi all,
    Can we handle exceptions for the expressions in select query.
    I created a view, there I am extracting a substring from a character data and expected that as a number.
    For example consider the following query.
    SQL> select to_number( substr('r01',2,2) ) from dual;
    TO_NUMBER(SUBSTR('R01',2,2))
    1
    Here we got the value as "1".
    Consider the following query.
    SQL> select to_number( substr('rr1',2,2) ) from dual;
    select to_number( substr('rr1',2,2) ) from dual
    ORA-01722: invalid number
    For this I got error. Because the substr returns "r1" which is expected to be as number. So it returns "Invalid number".
    So, without using procedures or functions can we handle these type of exceptions?
    I am using Oracle 10 G.
    Thanks in advance.
    Thank you,
    Regards,
    Gowtham Sen.

    SQL> select decode(ltrim(rtrim(translate(substr('r21', 2, 2), '0123456789', ' ' ), ' '), ' '), null, (substr('r21', 2, 2)), null) from dual;
    DE
    21
    SQL> ed a
    SQL> select decode(ltrim(rtrim(translate(substr('rr1', 2, 2), '0123456789', ' ' ), ' '), ' '), null, (substr('rr1', 2, 2)), null) from dual;
    D
    -

  • How to handle exceptions of rfc in web dydnpro

    hi all,
    i want to handle exceptions of Remote function module in webdynpro.how can we do that one.are there any variables in model class for those exceptions.
    regards
    Naidu

    Hi,
    Hope the following snippet answers ur query
    IWDMessageManager manager = wdComponentAPI.getMessageManager();
                   try{
                        wdContext.currentB_Quotation_Createfromdata_InpElement().modelObject().execute();
                        wdContext.nodeOutputQuotation().invalidate();
                   } catch(WDDynamicRFCExecuteException ce) {
                        manager.reportException(ce.getMessage(), false);

  • Handling exception logging in a Java task scheduler program?

    I need to design a Task Scheduler Where
    1) User should be able to schedule multiple task at the same time.
    2) There should be proper error handling on failure of any task and should not affect the other running tasks.
    I found the related programme at http://www.roseindia.net/java/example/java/util/CertainAndRepeatTime.shtml
    My concern is about handling of point 2 in program provided at above link. Say I schedule a recurring mail send process in above program which will be run first time on 12 september 2011 at 2 am, and will be repeated after every 2 hours Say a one process fais at 8 am. I want to log it in log file with task name and time details. Now if I look at above programme i.e CertainAndRepeatTime.java. This program will exit once it schedules all the tasks. Where and how should handle the logging?
    Posted at http://stackoverflow.com/questions/7377204/handling-exception-logging-in-a-java-task-scheduler-program but folks suggesting Quartz scheduler . My Limitation is that i can't for quartz because my project allows me to use only standard java library. Is there any way we can handle logging in the same programme in case of exception.

    Well, first of all I wouldn't trust any code from roseindia. So you might want to look for more reliable advice.
    As for your logging, you can add it for example to the TimerTask itself. I don't recommend adding logging to that roseindia cr*p though.

  • How to handle exceptions in a Service

    Hi,
    I'm trying to get the new Service (background thread) stuff working and am close but I have a problem with handling exceptions that are thrown in my Task. Below is my code, does anyone know if I am doing something wrong, or is this just a flaw in the system at the moment:
    Here is my service:
    public class TestService extends Service<String>
        protected Task<String> createTask()
            return new Task<String>()
                protected String call() throws Exception
                   System.out.println("About to throw exception from inside task");
                   throw new Exception("Test failure");
    }Here is my code using this service:
    public void doTest()
        final TestService test = new TestService();
        test.stateProperty().addListener(new ChangeListener<Worker.State>()
            public void changed(ObservableValue<? extends Worker.State> source, Worker.State oldValue, Worker.State newValue)
                System.out.println("State changed from " + oldValue + " to " + newValue);
        test.start();
    }When the task throws its exception I was hoping to get a state change to FAILED but the callback is never triggered. I've tried listening for invalidation of the state and also tried listening to all the other properties on Service (running, progress, exception, etc). There doesn't seem to be any feedback after the exception has been thrown.
    Am I using this wrong, or is it a bug?
    Cheers for you help,
    zonski

    Hi,
    This was working in the build #32. I updated the JavaFX to build #36 and it stopped working.
    I checked in the latest build #37 as well which was released last week and this doesn't work here as well.
    If the task is succeeding the state is getting changed to SUCCEEDED but in case of an exception there is no change in the state
    Edited by: user12995677 on Aug 3, 2011 2:07 AM

  • How can I handle exception? - to give user more friendly notification

    Hi!
    User gets an error:
    'Error in mru internal routine: ORA-20001: Error in MRU: row= 1, ORA-20001: ORA-20001: Current version of data in database has changed since user initiated update process. current checksum =...'
    How can I handle this exception (when two users want to modify the same set of data at the same time)? I would like to hide the above error message and give user more friendly notification.
    Thanks in advance,
    Tom

    Thanks Vikas for your answer.
    These workarounds are really creative and I want to use one of them. BUT my problem is to 'catch' the exception/error when two users want to modify the same set of data at the same time.
    Those solutions which we can read about in this link you gave me describe handling exceptions in pl/sql processes. How can I catch the error I am talking about in pl/sql code?
    Code would be like this:
    DECLARE
    two_users EXCEPTION;
    BEGIN
    IF --catch the error
    THEN RAISE two_users;
    END IF;
    EXCEPTION WHEN two_users
    THEN :HIDDEN_ITEM := 'Error Message';
    END;
    What should I put in a place where there is '--catch the error' ??
    Thanks in advance,
    Tom

  • Handling exceptions inside a Presentation

    Hi people, I have a problem handling exceptions inside a Presentation that it is inside an screenflow (that it is inside a Global Creation Activity). This it is in some way related to this other thread: Managing transactions with DynamicSQL
    I have an Interactive Activity that renders an Object BPM's Presentation. This Presentation has dependent combos (i.e.: Country, State, City).
    Although I can add an exception transition to the Interactive Activity, if the BP-Method that fills the other combo fails, this exception transition it is not executed. Instead, it shows a screen with the stack trace.
    The solution I've found: catch the exception inside the BP-Method, and use this.showError let the user know that something went wrong.
    This solves my problem, but I'd like to know why ALBPM let me put an exception transition from an Interactive Activity? I mean, in which cases this transition could be executed
    Thanks in advance!

    This does not solve my problem, but I think that it would be a better design idea not to allow presentations to call server-side BP-Methods directly. Instead it should call a client-side BP-Method and from this method call the one in the server.
    This should improve the way we can handle an error that occurs on a server-side BP-Method
    It's for sure a "best practice", but I think it would be better if the tool help us to implemented this way
    What do you think?

  • To handle exception in insert query

    Hi ,
    I am trying it insert certain records from another table A to temp table B, while doing insert i am having exception of unique constraint in table B how can i check which record is throwing exception while inserting in table A
    for eg:
    insert into A
    select * from B;
    i need to handle exception in which record of B i am getting unique constraint error

    Hi,
    If you add an error logging clause (with keywords LOG ERRORS), then you can insert a row into another table for each row that can't be inserted according to your INSERT statement.
    To query table A to see which ids already exist in table B, you can say
    SELECT  *
    FROM    a
    WHERE   a_id  IN (
                          SELECT  b_id
                          FROM    b
    where b.b_id is the unique key in table b, and a.a_id is the value you're truing to insert into that column.
    If you just want to skip the insert when a matching row already exists, then use MERGE instead of INSERT.

  • Problem with  Handling  Exception  in Jsp

    hi
    I am unable to handling exception in Jsp.
    In my Simple Form i taken a simple text field named salary.
    Details.jsp
    <%@ page language="java" isErrorPage="true" errorPage="Det.jsp"%>
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
    <html:html>
    <html:form action="/det.do">
    Enter Salary<html:text property="sal"/><br>
    <br>
    <html:submit value="SEND" />
    </html:form>
    </html:html>and my Actionclass is:
    package com.gurukul.util;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    public class DetUserAction extends Action {
         String s=null;
         int sal;
    public ActionForward execute(ActionMapping map,ActionForm form,HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
         try
         sal=Integer.parseInt(req.getParameter("sal"));
         if (sal>0)
              s="success";
         else
         throw new SalException(sal);}
         catch(SalException e)
              e.getMessage();
         return map.findForward(s);
    and my Formbean is
    package com.gurukul.util;
    import java.io.IOException;
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import org.apache.struts.action.Action;
    import org.apache.struts.action.ActionForm;
    import org.apache.struts.action.ActionForward;
    import org.apache.struts.action.ActionMapping;
    public class DetUserAction extends Action {
         String s=null;
         int sal;
    public ActionForward execute(ActionMapping map,ActionForm form,HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
         try
         sal=Integer.parseInt(req.getParameter("sal"));
         if (sal>0)
              s="success";
         else
         throw new SalException(sal);}
         catch(SalException e)
              e.getMessage();
         return map.findForward(s);
    }and my struts-config.xml is
                                  </form-bean>
                                  <form-bean name="DetUser"  
                           type="com.gurukul.util.DetUserForm">
                                  </form-bean>
    <action path="/det"
                          type="com.gurukul.util.DetUserAction"
                          name="DetUser"
                        input="/Details.jsp"
                           scope="request">
                           <exception key="errors.sal"
                           type="com.gurukul.util.SalException"
                           path="/jsp/Det.jsp"/>
                       <forward name="success" path="/jsp/DetailList.jsp"  />
                       <forward name="failure" path="/jsp/Details.jsp"/>
                         </action>and Det.jsp(i.e error jsp) is
    <%@ page language="java" isErrorPage="true"%>
    <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html"%>
    <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean"%>
    <html:html>
    <center><b>
    Invalid Salary</b></center>
    <%= exception.getMessage() %>
    </html:html>but i didnt get exception on jsp.
    please help me
    Regards
    VAS

    hi
    can you please guide me how to handle exceptions in Jsp(struts)?

  • Can we handled exceptions in Oracle EDQ?

    Hi All,
    I need to know, how to handle exceptions in EDQ? for example when i am fetcthing data from DB view, DB is down/ process is hanged then i have to send error msg to Webservice.
    How can i handled this situation? Thanks in advance.
    Regards,
    Chandra

    Hi,
    This can be done, using the Triggers functionality, and a trigger that detects a certain type of error in a log and calls a web service.
    Someone more experienced than me in writing triggers would probably need to help with an example.
    Regards,
    Mike

  • Handle Exceptions during the Render Response phase

    Hi,
    How can we handle exceptions that occur during the render response phase, e.g. to redirect the user to an error page?
    In our application we have an unbounded taskflow with one page (jspx). It's quite a simple page, as it only displays some data from a managed bean.
    When we run the application and e.g. throw explicitly a RuntimeException form one of the getters, all we get is the 'progress indicator', not even a stacktrace on the page (only in the logs).
    Unfortunately, it doesn't seem possible to handle the exception, not via the taskflow Exception Handler, the web.xml error-page or a custom ADF Controller exception handler. In the latter case, we can catch the exception but when we try a redirect (on the external context or response) we get a 'java.lang.IllegalStateException: Response already committed' exception.
    Any suggestions?
    Ciao
    Aino

    Hi Aino
    I'm not sure if that's the problem, but I recently read somewhere (wish I remember where) an IllegalStatementException that was throwing because there was no entry page defined in web.xml.
    If you are trying that, remember that web.xml doesn't support .jspx pages.
    Edited by: TheCrusader on 09-jul-2010 15:03
    Edited by: TheCrusader on 09-jul-2010 15:10

  • What is the best way to handle Exception in Java?

    We are designing an application that will be developed using JSP + EJB .
    To deal with the exception part, we have thought about following solutions
    (1)All methods in EJB will be declare with throws clause, with the respect to the potential exceptions that can be thrown by method.
    We will catch only those exceptions, for which we can take alternative steps or further action when they occurred. All other exceptions will be thrown to the caller.
    (2)All JSP pages will have try/catch that catches exceptions thrown by EJB or by JSP code.
    (3)A common JSP file will be designated to handle Exception by setting isErrorPage property true and all JSP files are pointing to that particular file for exception handling.
    (4)Whenever any exception occurred in application, it will bubbled up and end user will get a common JSP page designed to handle exception.
    I am looking for the suggestions to improve this mechanism.
    Regards,
    Chetan

    The problem with the standard expection handling in a web environment is that all the potentially useful status information goes to the user, who probably won't make head nor tail of it. It also goes to the logs which someone might, or might not get arround to reading.
    What I do is to have a standard method called to deal with unanticipated exceptions and e-mail me a status report. This contains not just the extended stack trace (chasing any level of wrapped exception) but also details of the transaction being processed, including the user if known.
    Set up an e-mail alias with a list of people to receive these reports. Often you can have the problem fixed, and send the user an apologetic e-mail before they even get a complaint in.
    Create JSP tags to do this with any other per-page housekeeping.

  • How to handle exceptions in web dyn pro

    Hi Frndz....
                     Can any one kindly xplain how to handle exceptions in web dyn pro..like we hav exceptionhandling in java ....so is there any for NWDS
    THANKS & REGARDS
    Rajesh

    Hi,
    Web Dynpro Java is basically java only.i.e You program in java. Hence exceptions are supported in the same way as in java i.e. via try,catch and finally block.
    Additionally,
    In 04/04s if you create a method in any controller in web dynpro you cann't specify exception that can be thrown in the method. This is now possible in new programming web dynpro model in CE.
    Hence when creating a method you can also specify custom or core java (lib)excetions.
    Regards,
    Ashwani Kr Sharma

  • Handling exception in custom components

    Hello,
    Is there any info about handling exceptions in custom components? I would like to expose some exceptions to the Livecycle process.
    Thank you

    I have faced this situation for a while and found solution.
    1.Create your custom Exception say (custom exception)
    2. Set the properties like errorcode,errormessage, and throwable (if u want to bubble up the exceptions).
    3. Create a custom object to hold the results (i.e like a java bean)
    4. In your custom component methods just return the custom object and set exception as a property.
    for e.g.
    public class CustomReturn {
    private String result;
    private CustomException exception;
    //getters & setters
    public class CustomException {
    private int errorCode = -1;
    private String errorMessage;
    private Throwable error;
    //getters & setters
    public class CustomClass {
    public CustomReturn testValue() {
    CustomReturn returnValue = new CustomReturn();
    try {
    //perform operations
    catch(Exception ex) {
    CustomException cex = new CustomException ();
    cex .setErrorCode(1000);
    cex .setErrorMessage(ex.getMessage());
    cex .setErr(ex);
    returnValue .setException(cex);
    return returnValue;
    return returnValue;
    As you see , you can check for the exception in your return type using the bean property.
    This will overcome the limitation of not able to retrieve the error stack incase of errors with default livecycle components.
    Hope this helps.
    -Senthil

  • How to handle exception in struts

    i am using global exception to pass to a page that shows an error message.
    I also want to pass the actual error message to that page is that possible
    through the struts config
    <global-exceptions>
    <!-- global exception handler -->
    <exception
    key="global.message"
    type="java.lang.Exception"
    path="Errors.jsp"/>
    </global-exceptions>

    i am using global exception to pass to a page that shows an error message.
    I also want to pass the actual error message to that page is that possible
    through the struts config
    <global-exceptions>
    <!-- global exception handler -->
    <exception
    key="global.message"
    type="java.lang.Exception"
    path="Errors.jsp"/>
    </global-exceptions>

Maybe you are looking for

  • Transfer images from mac to camera

    Hi, im trying to transfer images from my macbook pro back to my camera. When i hook up the camera the only place i can see it is in i photo and it wont allow me to transfer in that program. The camera does not sure up on my desktop as a flash drive w

  • Wrapper on Ajax Libraries

    Is there any wrapper built on Ajax Libraries like Dojo, JQuery etc that can be included in jsp to deal with Ajax. I want to include Ajax in my JSPs. What would be the best library to use? Urgent respnose needed please.......... Thanks, Usman Ashraf B

  • ISE Voip phones: authentication failed against AD

    the message is 2064 Authentication method is not supported by any applicable identity store(s): Authentication failed the user is present on AD and testing user in ise is ok the authentication rule to check in AD is created policy servers are joined

  • How to rearrange images in a contact sheet?

    How do I rearrange images in a contact sheet? I am trying to drag them to the square I want but nothing happens.

  • Orarrp utility platform support

    I was wondering if ORARRP was supported on Linux when Reports are called from a Oracle Form. When I run a report from within my form, it opens the browser with the RRPA file just fine but the printer dialog never comes up. When I move the file down t