Throwing my  own exception

I'm trying to throw my own exception but can't seem to do it. the method i'm using has three different exceptions that i need to declare. Heres my code with one exception (not working of course):
     public static String ProcessUserInput(){          
          BufferedReader kbd = new BufferedReader(new InputStreamReader(System.in));
          String line = "";
          BlankException blanke = new BlankException blanke();
          try{
line = kbd.readLine();
catch (IOException ex)
System.out.println( "Error reading keyboard input." );
return line;
I've tried to throw a new exception called BlankException but i get the following error message:
'(' or '[' expected
BlankException blanke = new BlankException blanke();
How do i put three of my own exceptions in this piece of code?

how do i do that if i have three exceptions in the one methodYou can declare your method to throw as many exceptions as you want.
Example:public void method() throws CustomExceptionA, CustomExceptionB, CustomExceptionC {
    if (/* something goes wrong */) {
        throw new CustomExceptionA();
    try {
    catch(IOException ioEx) {
        throw new CustomExceptionB();
    catch(Exception ex) {
        throw new CustomExceptionC();
}

Similar Messages

  • Doubt on Throwing own exceptions in java rmi?

    Hello,
    I am writing my own exception class and want to send exception object to the specific client.
    But, Exception class constructor only accept string.
    If I want to send both string and its corresponding error constant, how can I throw it.
    thank you.

    But, Exception class constructor only accept string.That is simply untrue. Have another look.

  • N00b query: Why would anyone ever want to define their own Exception class?

    I've been reading thru my Java textbook for the past couple hours.
    Exceptions are a wonderful thing. I already found several instances where I could've implemented try/cacth in my earlier programs.
    Anyway, getting back to the point. My question is, can someone give me a realistic situation/example where a custom Expcetion class is REQUIRED? (the key word here is "required"!)
    I can see why someone would want to have his own Exception class..... e.getMessage() as custom error messages are SO DAMN COOL!!!!!! :P
    hehe
    But seriously, if you are making intermidiate/advanced Java programs, would you ever REQUIRE to make your own Exception class? Afterall, even a custom made Exception class always "extends" from a pre-defined Java class, right?
    Let me make this a bit more clear... public class CustomException extends IOException{  }Now, if I am making a try/catch statement, I can simply say
    try{
    throw new CustomException;
    catch (IOException e) { }
    Now as you can see, the CustomException was caught by the catch claus, because IOException is the superclass of CustomException. So, in other words, the whole CustomException thingy didnt do anything useful.
    I know I know, I am so naive. Enlighten me >.<

    Sure. Say you want to have a system where you want to include a custom error code which maps to some internationalized error messages. You would create an Exception subclass with a field to hold that value separate from the normal "default" message. Then you could throw that exception in all your code. Other code can catch it as a plain Exception if they want and use the "default" message, which is okay if they don't really care about the error code.
    I don't think you are ever "required" to make your own exceptions. I have done so, but I don't often. It depends. See, there are plenty of Exception subclasses in the standard packages, and most of them cover many of the things you need. So more often if I'm throwing an exception, I'll be using the already existing ones, like IllegalArgumentException or IOException (whatever is relevant to the code).
    Yes, you can do what you did below with CustomException. However the reason you might do that is cuz you really want to do this:
    try {
       // call some code that may throw IOException from some standard IO package
       // or may throw CustomException from some of my methods...
    } catch (CustomException ce) {
       // handle cusotm exception
    } catch (IOException ioe) {
       // handle IO exception
    }Cuz you may want to differentiate between your exceptions vs. IOExceptions that might be thrown from some java.io class.
    Usually when you use an exception class it's a named class that relates to some condition. It may hold additional information besides the standard message, but I think most of the time it's just the class name which describes the problem. And if there isn't one that describes the problem that you're code might encounter, then create a subclass.

  • Defining own exception

    Hi,
    I need to create an exception that will be thrown if a call to function x returns a negative value. I assume that means I need to create my own exception class. However, everything I've read about creating one's own exception class involves merely changing the text thrown by a given exception. How does one actually define an exception which says "Throw this when x is a particular value"?
    Any suggestions?
    Cheers,
    Didje

    You detect the fault yourself, and throw it. Eg
    public class NegativeException extends Exception {
       public NegativeException() {
         super("negative number");
    // in code elsewhere
    if ( getValue() < 0 ) throw new NegativeException();

  • WPUMFactory.getUserFactory() throws null pointer exception

    Hi,
    I am trying to use KM API's to read files from KM repository. I am using the below code as mentioned in the blog: How to download KM documents using Web Dynpro Java
    Below is my code:
    IWDClientUser wdClientUser = WDClientUser.getCurrentUser();
    com.sap.security.api.IUser sapUser = wdClientUser.getSAPUser();
    IUser epUser = WPUMFactory.getUserFactory().getEP5User(sapUser);
    However the line WPUMFactory.getUserFactory() throws null pointer exception. Can some one please help on why these happens as these seems to be the standard code to read a file from KM.
    Thanks.
    Regards,
    Ponraj M

    Hi Ponraj ,
    Instead of fetching the current logged on user , use the below line to set the resource context and see if it helps .
    com.sapportals.wcm.repository.IResourceContext resourceContext = ResourceFactory.getInstance().getServiceContext("cmadmin_service");
    cmadmin_service is a existing user that can be used to access KM resources .
    Regards
    Mayank

  • Creating own Exception class

    In my past paper it says...
    Show how to create your own Exception class that derives from class Exception. The class should provide a default constructor which allows a "My Error message" message to be set, and a second constructor which has as an argument the error message. 4-MARKS
    Does this look right..?
    public class MyExcep extends Exception
         public MyExcep()
              super("My Error Message");
         public MyExcep(String message)
              super(message);
    }

    Yes. Do I get 4 marks now? or is it Four Marks?

  • How to throw a permanent exception during mapping?

    I'm using the java coding: "throw new RuntimeException(message);" to trigger an error during mapping.
    This will set the message status to: "System error, manual restart possible".
    How can I throw a permanent exception during mapping? So that the message is set to error but will NOT be restartable.

    Hi,
    Any error in  asynchronous mode in XI will be in a Restart Mode.  I dont think this can be done.
    /people/alessandro.guarneri/blog/2006/01/26/throwing-smart-exceptions-in-xi-graphical-mapping
    /people/sap.user72/blog/2005/11/29/xi-how-to-re-process-failed-xi-messages-automatically
    Regards,
    Bhavesh

  • Vector.clear() throws null pointer exception

    is there anything wrong in my code. when i try to clear the vector irrespective of whether i add elements to it or not, if there are no elements added to the vector v1.clear() it throws null pointer exception
    Vector v1 = new Vector(1,1);
    v1.clear()

    And the guessing game continues... anyone for a shortctu to duplicate this problem?
    public class NullVectorCreator
        private Vector v1;//just love the name, so clear and unambiguous... :)
        public NullVectorCreator
             Vector v1 = new Vector();//well done - a local variable masquerading as
                                                          // a class member
        public Vector getVector()
             return v1;
        public static void main(String[] args)
               NullVectorCreator nvc = new NullVectorCreator();
                nvc.getVector().clear();//Why does this throw an NPE? why? java is bugged!
    }

  • ValuePattern.SetValue Throws ElementNotAvailableException (Inner Exception of InvalidOperationException)

    I have a Wpf FrameworkElement derived control that offers a custom AutomationPeer:
    using System;
    using System.Collections.Generic;
    using System.Text;
    using System.Windows;
    using System.Windows.Automation.Peers;
    using System.Windows.Automation.Provider;
    namespace TSystem.Content
    internal class MarkTopicElementAutomationPeer : FrameworkElementAutomationPeer, IValueProvider
    private static readonly Dictionary<string, TcsMarkStates> StringToStateMap = new Dictionary
    <string, TcsMarkStates>
    {"Positive", TcsMarkStates.Positive},
    {"Negative", TcsMarkStates.Negative},
    {"Neutral", TcsMarkStates.Neutral}
    #region Constructors
    public MarkTopicElementAutomationPeer(FrameworkElement owner) : base(owner)
    if (!(owner is MarkTopicElement))
    throw new ArgumentException("Owner must derive from MarkTopicElement");
    #endregion
    #region Automation Peer Overrides
    protected override string GetNameCore()
    StringBuilder name = new StringBuilder();
    name.AppendFormat("MarkTopicElement:{0}:{1}", OwnerAsElement.Caption, OwnerAsElement.ElementID);
    Topic parentTopic = OwnerAsElement.FindLogicalAncestorByType<Topic>();
    if (null != parentTopic)
    name.AppendFormat(":ParentTopic:{0}:{1}", parentTopic.GetType(), parentTopic.Instance);
    return name.ToString();
    public override object GetPattern(PatternInterface patternInterface)
    return patternInterface == PatternInterface.Value ? this : base.GetPattern(patternInterface);
    protected override AutomationControlType GetAutomationControlTypeCore()
    return AutomationControlType.ComboBox;
    protected override bool IsContentElementCore()
    return true;
    protected override bool IsControlElementCore()
    return true;
    #endregion
    #region IValueProvider Implementation
    public bool IsReadOnly
    get { return OwnerAsElement.ReadOnly; }
    public void SetValue(string value)
    OwnerAsElement.ChangeMarkState(StateFromString(value));
    public string Value
    get { return OwnerAsElement.MarkState.ToString(); }
    #endregion
    #region Helper methods
    private MarkTopicElement OwnerAsElement
    get { return (MarkTopicElement) Owner; }
    private static TcsMarkStates StateFromString(string value)
    TcsMarkStates state;
    return (StringToStateMap.TryGetValue(value, out state) ? state : TcsMarkStates.Neutral);
    #endregion
    However, when I try to access its implementation the ValuePattern:
    WpfComboBox mark = HistoryPage.UIEVSite234Window.UIHostedPageWindow.UIItemCustom.UIItemCustom11.StartedTopic.StartedJustPTA;
    var markElement = (AutomationElement) mark.NativeElement;
    ValuePattern pattern = (ValuePattern) markElement.GetCurrentPattern(ValuePattern.Pattern);
    pattern.SetValue("Positive");
    It throws this exception:
    Result Message: 
    Test method EVTCSTest.HistoryStartedTest.SetStartedToPositive threw exception:
    System.Windows.Automation.ElementNotAvailableException: Element not available ---> System.InvalidOperationException: Operation is not valid due to the current state of the object.
    Result StackTrace: 
    at UIAutomationClient.IUIAutomationValuePattern.SetValue(String val)
       at System.Windows.Automation.ValuePattern.SetValue(String value)
     --- End of inner exception stack trace ---
        at System.Windows.Automation.ValuePattern.SetValue(String value)
       at EVTCSTest.HistoryStartedTest.SetStartedToPositive() in c:\Development\zTest\EVTCSTest\EVTCSTest\HistoryStartedTest.cs:line 46
    Any ideas why this may be?  I know that the element is enabled and is not read only.
    One final update...I have confirmed that it is getting to my implementation of the read-only Value property of my automation peer.  However it doesn't seem to even be reaching my implementation of SetValue.
    Thanks,
    Kelly Hilliard

    Hi,
    Based on your description, I don’t think that the issue is really related to Coded UI test itself. Your issue is mainly on setting a value using ValuePattern.SetValue. I think it is more related to accessibility and automation. I noticed that you post a
    new thread on Windows Desktop Development for Accessibility and automation forum:
    http://social.msdn.microsoft.com/Forums/windowsdesktop/en-US/8c8f4566-22df-4944-ba57-13898dcec6be/valuepatternsetvalue-throws-elementnotavailableexception-inner-exception-of?forum=windowsaccessibilityandautomation#8c8f4566-22df-4944-ba57-13898dcec6be
    I am not an expert on accessibility and automation, I am sorry for that I can’t provide you something useful about ValuePattern.SetValue method’s usage. I think that community members on Windows Desktop Development for Accessibility and Automation forum
    will help you resolve this issue better.
    Thank you for your understanding and support.
    Best regards,
    We are trying to better understand customer views on social support experience, so your participation in this interview project would be greatly appreciated if you have time. Thanks for helping make community forums a great place.
    Click
    HERE to participate the survey.

  • How can I define a own exception

    Hallo,
    I want to delete rows in a table after pressing the "Delete"-Button.
    When pressing "delete" the message box htmldb_delete_message is shown.
    When pressing "Ok" the row will not deleted if there are depending rows in another table. On the Form the Error "ORA-02292: Integritäts-Constraint (EV_ADM.SEM_TEILNAHME_PN_FK) verletzt - untergeordneter Datensatz gefunden" is displayed. For this ORA--message I want to create a own exception and displays a message that the user can understand. How can I do this?
    Thanks, Daniela

    See also
    how to avoid ora-errors to be displayed
    for a similar discussion, and a solution. Follow also the links in teh posts !
    Leo

  • Should a signed applet ever throw a security exception?

    hi,
    I've had a few times when a signed applet seems to throw a security exception (at the moment am trying to figure out a SocketException being thrown).
    I thought if the applet was signed, and when the browser asks if you want to grant it permissions you press Yes (which I do), then there should not be any security issues?
    thanks,
    asjf

    A signed applet has to assert which permissions it wants. The client JVM then asks the user if they will give those permissions to the signer. If the applet tries to do something for which it hasn't been granted permission a security exception is thrown.

  • How to throw a SOAP exception

    Hi,
    I have a requirement from customer that when they call the WSDL from their app and the workflow will not get what it should, that it should throw standard SOAP exception.
    To give more details on it, they will send for example input string "A" and based on that I will return output string "B" in the process.
    Now if they ask for "C" for instance, I need to be able to throw that SOAP exception. Is that possible? The process in workbench consists of simple decision point and set value activity based on route conditions.
    Thanks
    J.

    I am assuming you are wanting something to come back as a SOAP fault element?
    Unhandled process exceptions are sent back as faults. So, theoretically, you could write a service component to do nothing but throw an exception. Then you could route your process to call that in specific situations.
    As an alternative, I would consider having something like an additional 'status' output variable that always came back in the response which indicated the status of your process.
    Good Luck,
    Ryan M. Jacobs
    [email protected]
    Cardinal Solutions Group

  • HttpURLConnection throws a FileNotFound exception

    Hi Everybody,
    I want to post the data to a remote servlet using HttpURLConnection.
    But it throws a FileNotFound exception. Pls send me the solution.
    My code is
    First Servlet:
    ==============
    import java.io.*;
    import java.net.*;
    import java.text.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class Test extends HttpServlet {
         public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws IOException, ServletException {
    response.setContentType("text/html");
              URL url = new URL("http://node_18:8080/examples/servlet/HelloWorldExample1");
              HttpURLConnection conn = (HttpURLConnection) url.openConnection();
              conn.setRequestMethod("POST");
              //HttpURLConnection.setFollowRedirects(true);
              conn.setUseCaches(false);
              conn.setDoOutput(true);
              conn.setDoInput(true);
              String postData = "name=value&othername=value";
              String lengthString = String.valueOf(postData.length());
              conn.setRequestProperty("Content-Length", lengthString);
              conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
              Writer out = new OutputStreamWriter(conn.getOutputStream());
              out.write(postData);
              out.close();
              PrintWriter out1 = response.getWriter();
              BufferedReader in =
              new BufferedReader(new InputStreamReader(conn.getInputStream()));
              String line = null;
              while (null != (line = in.readLine()))
              out1.println(line);
              in.close();
              out1.close();
    Second Servlet:
    ================
    import java.io.*;
    import java.text.*;
    import java.util.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    public class HelloWorldExample1 extends HttpServlet {
    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String name = request.getParameter("name");
    String othername = request.getParameter("othername");
    System.out.println("name = "+name+" othername = "+othername);
    out.println("<html>");
    out.println("<head>");
         out.println("<title> Test </title>");
    out.println("</head>");
    out.println("<body bgcolor=\"white\">");
         out.println("Test");
    out.println("</body>");
    out.println("</html>");
    public void destroy() {
         System.out.println("Servlet Destroyed");
    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException
         doPost(request,
    response);
    Error:
    =======
    java.io.FileNotFoundException: http://node_18:8080/examples/servlet/HelloWorldExample1
         at sun.net.www.protocol.http.HttpURLConnection.getInputStream(HttpURLConnection.java:574)
         at Test.doGet(Test.java:37)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:740)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:853)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:247)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at filters.ExampleFilter.doFilter(ExampleFilter.java:149)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:213)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:193)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:260)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:471)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardContext.invoke(StandardContext.java:2396)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:180)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.valves.ErrorDispatcherValve.invoke(ErrorDispatcherValve.java:170)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:172)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:641)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:174)
         at org.apache.catalina.core.StandardPipeline$StandardPipelineValveContext.invokeNext(StandardPipeline.java:643)
         at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:480)
         at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:995)
         at org.apache.coyote.tomcat4.CoyoteAdapter.service(CoyoteAdapter.java:223)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:405)
         at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.processConnection(Http11Protocol.java:380)
         at org.apache.tomcat.util.net.TcpWorkerThread.runIt(PoolTcpEndpoint.java:565)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:623)
         at java.lang.Thread.run(Thread.java:484)

    Hi p200002,
    I call doPost method in doPost in the second servlet. It will be
    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws IOException, ServletException
         doGet(request,
    response);
    }

  • Purpose of throws clause in exception handling

    hi all,
    I have written a sample code for exception handling...please refer below....
    class a
    void fun() throws ArithmeticException
    int i=0;
    i=10/0;
    class exec
    public static void main(String a[])
    a a1=new a();
         try{a1.fun();}
         catch(ArithmeticException e){System.out.println("hi");}
    }

    I read the article...and came out with these points...
    1..If method is throwing an unchecked exception (as in this case) then there is no need for throws clause, if you are not catching it then and there only.....
    2...if a method is throwing a checked exception then either you need to catch it then and there only or you must specify a throws clause for the same in function definition......*And the purpose of not catching it then and there only is*
    "For example, if you were providing the ListOfNumbers class as part of a package of classes, you probably couldn't anticipate the needs of all the users of your package. In this case, it's better to not catch the exception and to allow a method further up the call stack to handle it."
    M I RIGHT??

  • Wehre can i find all the throw and catch exceptions

    I havent had much success figuring out which predefined exceptions i should/can use. Can someone please guide me where i can find out what kind of throw and catch exceptions are there in java and how and where can i find them. thanks.

    Read this first: http://java.sun.com/docs/books/jls/second_edition/html/exceptions.doc.html#44044
    You can't find them all anywhere. You'll just encounter them as you use different APIs.
    One of the most basic concepts around exceptions has to do with the difference between checked and unchecked exceptions. Any exception that extends RuntimeException is unchecked. Which means that if you call a method that throws an unchecked exception, you don't have to provide a catch block. These exceptions are usually thrown for things that could be avoided, i.e. programmer error.
    The compiler will require you to have a catch block for all checked exceptions. This means you should take steps in your code to handle them and retry the operation, such as user errors.

Maybe you are looking for

  • HP 8500 Printer and Connection to eprint server

    Refurbished Printer: HP Officejet Pro 8500 Premium A910 n (Changes status from new to refurbished 02-17-2011) ISP: ATT DSL Modem/Router: 2wire new from Best Buy. It is white with ATT logo on it. Is using latest firmware. Network: ethernet The printer

  • Keystore config error: keystore entry alias is not specified

    Hi all, I have been using the java keytool to genkey, do certreq and import the signed cert so far. I am now at the stage of using WebLogic admin console to configure the keystore to use this keystore. I am using WLS9.0. At the Keystore Config page,

  • How to show/hide TOC in CP8

    I would like to include a TOC which allows the learner to hide or show it. I added a basic TOC to my project, but don't know how to insert a show/hide function.  Thanks for your help! Paula

  • Automatic listing of 'title' on web page

    I want each page title listed elsewhere on the web page. The template used to create the page should have a title variable listed so when I give the new page a title, it automatically is listed in the desired location, with proper CSS formating.

  • Macbook Hard drive exchange?

    I have 2 Macbooks and one had died.  I tried to switch the hard drives in order to salvage my information.  The computer wouldn't boot with the new hard drive--maybe because I also tried to upgrade the memory.  Dead computer is: Apple MacBook 13.3" C