Java101: Catching and Handling Exceptions question

Dear all,
I am learning java from http://java.sun.com/docs/books/tutorial/essential/exceptions/putItTogether.html
However, I think the code in ListOfNumbers may have some problem, I put void in front of the function, but still have error. Could you please tell me any problem in the program?
thanks
import java.util.Vector;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.*;
public class Main {
    private Vector vector;
    private int SIZE = 10;
    public static void main(String[] args) throws IOException {
    public ListOfNumbers () {
        vector = new Vector(SIZE);
        for (int i = 0; i < SIZE; i++) {
            vector.addElement(new Integer(i));
    public void writeList() {
        PrintWriter out = new PrintWriter(
                            new FileWriter("OutFile.txt"));
        for (int i = 0; i < SIZE; i++) {
            out.println("Value at: " + i + " = " +
                         vector.elementAt(i));
        out.close();
        FileInputStream in = null;
        FileOutputStream out = null;
            in = new FileInputStream("xanadu.txt");
            out = new FileOutputStream("outagain.txt");
            int c;
            while ((c = in.read()) != -1) {
                out.write(c);
    public void writeList() {
    PrintWriter out = null;
    try {
        System.out.println("Entering try statement");
        out = new PrintWriter(
                       new FileWriter("OutFile.txt"));
            for (int i = 0; i < 5; i++)
                out.println("Value at: " + i + " = "
                             + vector.elementAt(i));
    } catch (ArrayIndexOutOfBoundsException e) {
         System.err.println("Caught "
                     + "ArrayIndexOutOfBoundsException: "
                     +   e.getMessage());
    } catch (IOException e) {
         System.err.println("Caught IOException: "
                             +  e.getMessage());
    } finally {
         if (out != null) {
             System.out.println("Closing PrintWriter");
             out.close();
         else {
             System.out.println("PrintWriter not open");
}

I have also post the error message here, I change the name of the file and the class name. I think I can not handle the error message #1 and #2. Please help me! Thanks
* Main.java
* Created on June 19, 2007, 10:54 AM
* To change this template, choose Tools | Template Manager
* and open the template in the editor.
package bytestreams01;
* @author Marco
import java.util.Vector;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.*;
public class Main {
    private Vector vector;
    private int SIZE = 10;
    public static void ListOfNumbers(String[] args) throws IOException {
    public ListOfNumbers () {
        vector = new Vector(SIZE);
        for (int i = 0; i < SIZE; i++) {
            vector.addElement(new Integer(i));
        FileInputStream in = null;
        FileOutputStream out = null;
            in = new FileInputStream("xanadu.txt");
            out = new FileOutputStream("outagain.txt");
            int c;
            while ((c = in.read()) != -1) {
                out.write(c);
    public void writeList() {
    PrintWriter out = null;
    try {
        System.out.println("Entering try statement");
        out = new PrintWriter(
                       new FileWriter("OutFile.txt"));
            for (int i = 0; i < 5; i++)
                out.println("Value at: " + i + " = "
                             + vector.elementAt(i));
    } catch (ArrayIndexOutOfBoundsException e) {
         System.err.println("Caught "
                     + "ArrayIndexOutOfBoundsException: "
                     +   e.getMessage());
    } catch (IOException e) {
         System.err.println("Caught IOException: "
                             +  e.getMessage());
    } finally {
         if (out != null) {
             System.out.println("Closing PrintWriter");
             out.close();
         else {
             System.out.println("PrintWriter not open");
}error message
init:
deps-jar:
Compiling 1 source file to C:\Users\Marco\bytestreams01\build\classes
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:29: illegal start of expression
public ListOfNumbers () {
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:29: invalid method declaration; return type required
public ListOfNumbers () {
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:41: <identifier> expected
in = new FileInputStream("xanadu.txt");
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:42: <identifier> expected
out = new FileOutputStream("outagain.txt");
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:45: illegal start of type
while ((c = in.read()) != -1) {
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:45: <identifier> expected
while ((c = in.read()) != -1) {
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:45: ';' expected
while ((c = in.read()) != -1) {
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:50: class, interface, or enum expected
public void writeList() {
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:53: class, interface, or enum expected
try {
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:55: class, interface, or enum expected
out = new PrintWriter(
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:57: class, interface, or enum expected
for (int i = 0; i < 5; i++)
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:57: class, interface, or enum expected
for (int i = 0; i < 5; i++)
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:57: class, interface, or enum expected
for (int i = 0; i < 5; i++)
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:61: class, interface, or enum expected
} catch (ArrayIndexOutOfBoundsException e) {
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:66: class, interface, or enum expected
} catch (IOException e) {
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:70: class, interface, or enum expected
} finally {
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:73: class, interface, or enum expected
out.close();
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:75: class, interface, or enum expected
C:\Users\Marco\bytestreams01\src\bytestreams01\ListOfNumbers.java:78: class, interface, or enum expected
19 errors
BUILD FAILED (total time: 0 seconds)

Similar Messages

  • How to catch and handle soap foult in a BPM process?

    Hi,
    I have a BPM process which calls a webservice in one of its activities. The webservice throws an exception so the response will contain a soap fault element. I defined exception handlers to handle the error but none of the exception handlers are called. How can I catch and handle these types of error?
    The log contains this:
    A component failed while executing activity '/Process1#Default-1.0/Automatic' (BP-method Automatic) over instance '/Process1#Default-1.0/3/0'.
    Details:
    The method 'CIL_automatic' from class 'BEA_Systems__Inc__.Process1.Default_1_0.Instance' could not be successfully executed.
    Caused by: <?xml version="1.0" encoding="UTF-8" ?>
    <MyException faultString="" faultCode="{http://schemas.xmlsoap.org/soap/envelope/}Server"/>
    fuego.lang.ComponentExecutionException: The method 'CIL_automatic' from class 'BEA_Systems__Inc__.Process1.Default_1_0.Instance' could not be successfully executed.
         at fuego.component.ExecutionThreadContext.invokeMethod(ExecutionThreadContext.java:498)
         at fuego.component.ExecutionThreadContext.invokeMethod(ExecutionThreadContext.java:251)
         at fuego.fengine.FEEngineExecutionContext.invokeMethodAsCil(FEEngineExecutionContext.java:214)
         at fuego.server.execution.EngineExecutionContext.runCil(EngineExecutionContext.java:1068)
         at fuego.server.execution.TaskExecution.invoke(TaskExecution.java:389)
         at fuego.server.execution.TaskExecution.executeCIL(TaskExecution.java:481)
         at fuego.server.execution.TaskExecution.executeTask(TaskExecution.java:655)
         at fuego.server.execution.TaskExecution.executeTask(TaskExecution.java:616)
         at fuego.server.execution.TaskExecution.executeTask(TaskExecution.java:152)
         at fuego.server.execution.activities.XAutomatic.execute(XAutomatic.java:60)
         at fuego.metadata.Activity.execute(Activity.java:1022)
         at fuego.server.execution.ToDoItemAutomatic.execute(ToDoItemAutomatic.java:35)
         at fuego.server.execution.DefaultEngineExecution$AtomicExecutionTA.runTransaction(DefaultEngineExecution.java:290)
         at fuego.transaction.TransactionAction.startBaseTransaction(TransactionAction.java:462)
         at fuego.transaction.TransactionAction.startTransaction(TransactionAction.java:540)
         at fuego.transaction.TransactionAction.start(TransactionAction.java:213)
         at fuego.server.execution.DefaultEngineExecution.executeImmediate(DefaultEngineExecution.java:117)
         at fuego.server.execution.DefaultEngineExecution.executeAutomaticWork(DefaultEngineExecution.java:57)
         at fuego.server.execution.EngineExecution.executeAutomaticWork(EngineExecution.java:42)
         at fuego.server.execution.ToDoItem.executeAutomaticWork(ToDoItem.java:264)
         at fuego.server.execution.ToDoItem.run(ToDoItem.java:531)
         at fuego.component.ExecutionThread.processMessage(ExecutionThread.java:754)
         at fuego.component.ExecutionThread.processBatch(ExecutionThread.java:734)
         at fuego.component.ExecutionThread.doProcessBatch(ExecutionThread.java:140)
         at fuego.component.ExecutionThread.doProcessBatch(ExecutionThread.java:132)
         at fuego.fengine.ToDoQueueThread$PrincipalWrapper.processBatch(ToDoQueueThread.java:432)
         at fuego.component.ExecutionThread.work(ExecutionThread.java:818)
         at fuego.component.ExecutionThread.run(ExecutionThread.java:397)
    Caused by: fuego.soaptype.SoapExecutionException: <?xml version="1.0" encoding="UTF-8" ?>
    <MyException faultString="" faultCode="{http://schemas.xmlsoap.org/soap/envelope/}Server"/>
         at fuego.soaptype.SoapCall.processRemoteException(SoapCall.java:531)
         at fuego.soaptype.SoapCall.invoke(SoapCall.java:292)
         at fuego.soaptype.SoapObject.invoke(SoapObject.java:272)
         at fuego.lang.Invokeable.invokeImpl(Invokeable.java:220)
         at fuego.lang.Invokeable.invoke(Invokeable.java:161)
         at BEA_Systems__Inc__.Process1.Default_1_0.Instance.CIL_automatic(Instance.java:265)
         at BEA_Systems__Inc__.Process1.Default_1_0.Instance.CIL_automatic(Instance.java:281)
         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 fuego.component.ExecutionThreadContext.invokeMethod(ExecutionThreadContext.java:491)
         ... 27 more
    Thanks,
    fifty

    Hi fifty,
    Did you get a solution to the above problem you have mentioned? I have a similar issue i am trying to fix.
    I have a webservice call in a process activity and if the call does not work i get a soap fault and the fuego.lang.ComponentExecutionException . My process requires that i catch the exception infact any kind of exceptions that occur on that call and perform another activity in the process.
    I have defined an exception handler at the activity level for java.lang.Exception and java.lang.RunTimeException.
    i don't see anything in the catalog which would handle the SOAP fault OR the componentexception.

  • ANN: Learn how to invalidate cache and handle exceptions

    http://otn.oracle.com/sample_code/tech/java/codesnippet/webcache/index.html
    These set of New OracleAS Web Cache How-to's illustrates how to invalidate cached content using esi:invalidate and PL/SQL invalidation tags. Also, learn how to esi exceptions using esi:try, esi:accept, and esi:except tags.
    Cheers,
    -Srikanth

    You may use any of the two ways:
    1. Use the interface. Go to Navigator, and go to that particular page where that portlet is, and then edit it. Go to Properties/Cache. See at the very bottom of the page for how to clear cache for that page.
    2. See details of the api function for cache invalidation.
    wwpro_api_invalidation.execute_cache_invalidation;

  • Catching and processing exceptions in a BPM

    All,
    I have several processing blocks in my BPM and each has its own exception defined. I'm checking exceptions in my blocks but would like to react differently for each of them.
    How can understand the values in an exception. I would like to send different sets of replies by exception data. How do I analysis what's stored in exception.
    I tried creating a simple string and assigned text via container operation. However, I cannot assign this to an interface (abs). So I'm stuck.
    thanks for all your replies!

    Hi Parimala,
    I had a similar requirement and let me write to you an option which i did
    and an option which could be used in when we upgrade to >SP15 (we are on Sp14 now).
    - I send out one message for all the excpetions, however, in the BPM send step i enter a value in the send context, which can be check in the configuration by checking the value for the context object "Process Step", and based on the different cases, i use different mapping programs(the process step is not available inside graphical mapping) and sends out different messages.
    - from SP15 onwards, there is a property in the send step in addition to the Send Context, which is a "Conversation ID". I can set these with different values for the different send steps based on where the exception occured...This varaible is accessible within the mapping program(this is part of the mapping runtime values like sender, receiver etc..)...and the string can be set accordingly..
    What SP version are you On??
    Thanks,
    Renjith

  • Add three stored procs in one big proc and add exception handling

    I have three proc's,
    1. sp_staging
    2.  sp_upload
    3. sp_process.
    Now, I have to create a new proc as sp_daily which has the other three proc's in it in the same order.
    if the first proc sp_staging fails, then the sp_daily proc should stop executing the other proc's which are in the order.
    CREATE PROCEDURE sp_daily
    AS
    BEGIN TRY
    EXEC sp_staging (already has EXCEPTION handling IN it)
    GO
    EXEC sp_upload (already has EXCEPTION handling IN it)
    GO
    EXEC sp_process (already has EXCEPTION handling IN it)
    GO
    END TRY
    BEGIN CATCH
    -- If any of the above proc's fail, the next proc's should not be executed
    END CATCH
    Something like this????

    Hi naveej,
    Whether the Stored Procedure sp_daily stops executing if the first sp_staging fails depends on how you code. To give a better demonstration, I will show the scenario that sp_upload runs with error. Please see the below code.
    --create the scenario
    USE master;
    IF db_id('TestDB') IS NULL
    CREATE DATABASE TestDB;
    USE TestDB;
    IF OBJECT_ID('T1') IS NOT NULL
    DROP TABLE T1;
    GO
    CREATE TABLE T1
    procName varchar(99)
    IF OBJECT_ID('sp_staging') IS NOT NULL
    DROP PROCEDURE "sp_staging";
    GO
    CREATE PROCEDURE "sp_staging" @denominator FLOAT
    AS
    BEGIN TRY
    DECLARE @quotient FLOAT;
    SET @denominator=1/@denominator; -- when @denominator=0, error occurs
    INSERT INTO T1 VALUES('sp_staging finished');
    END TRY
    BEGIN CATCH
    END CATCH
    GO
    IF OBJECT_ID('sp_upload') IS NOT NULL
    DROP PROCEDURE "sp_upload";
    GO
    CREATE PROCEDURE "sp_upload" @denominator FLOAT
    AS
    BEGIN TRY
    DECLARE @quotient FLOAT;
    SET @denominator=1/@denominator;
    INSERT INTO T1 VALUES('sp_upload finished');
    END TRY
    BEGIN CATCH
    DECLARE @ERRMSG VARCHAR(99);
    SELECT @ERRMSG=ERROR_MESSAGE()+'sp_upload failed, process continues';
    INSERT INTO T1 VALUES(@ERRMSG);
    END CATCH
    GO
    IF OBJECT_ID('sp_process') IS NOT NULL
    DROP PROCEDURE "sp_process";
    GO
    CREATE PROCEDURE "sp_process" @denominator FLOAT
    AS
    BEGIN TRY
    DECLARE @quotient FLOAT;
    SET @denominator=1/@denominator;
    INSERT INTO T1 VALUES('sp_process finished');
    END TRY
    BEGIN CATCH
    END CATCH
    GO
    IF OBJECT_ID('sp_daily') IS NOT NULL
    DROP PROCEDURE "sp_daily";
    GO
    CREATE PROCEDURE "sp_daily" @p1Deno FLOAT,@p2Deno FLOAT,@p3Deno FLOAT
    AS
    BEGIN TRY
    EXEC sp_staging @p1Deno;
    EXEC sp_upload @p2Deno;
    EXEC sp_process @p3Deno;
    END TRY
    BEGIN CATCH
    INSERT INTO T1 SELECT ERROR_MESSAGE()+'error captured by sp_daily';
    END CATCH
    GO
    --Test Example
    TRUNCATE TABLE T1;
    EXEC sp_daily 1,0,1;
    SELECT * FROM T1;
    We can judge from the rows in T1, sp_daily continued even when there came a error in sp_upload. The reason for the continuity is that the error which occurred in sp_upload was caught and handled by  sp_upload itself. Sp_daily's CATCH block didn't capture
    any error(we didnt see any row like "error captured by sp_daily") so  sp_dailys continued running with no interruption.
    Let’s make a little modification on the sp_upload. see the below code.
    ALTER PROCEDURE "sp_upload" @denominator FLOAT
    AS
    BEGIN TRY
    DECLARE @quotient FLOAT;
    SET @denominator=1/@denominator;
    INSERT INTO T1 VALUES('sp_upload');
    END TRY
    BEGIN CATCH
    DECLARE @ERRMSG VARCHAR(99),@ErrSeverity INT;
    SELECT @ERRMSG=ERROR_MESSAGE()+'sp_upload failed, process got terminated',@ErrSeverity=ERROR_SEVERITY();
    RAISERROR(@ERRMSG ,@ErrSeverity,1);
    END CATCH
    GO
    --Test Example
    TRUNCATE TABLE T1;
    EXEC sp_daily 1,0,1;
    SELECT * FROM T1;
    At this time,  sp_daily got terminated when  sp_upload encountered an error. Sp_upload didn’t handle the error, it threw the error instead. Then the CATCH block in  sp_daily caught  the error and interrupted sp_daily itself. If you don’t
    need to handle the error which may occur inside of the inner called procedures, the TRY and CATCH block in the procedure which calls them would be enough to catch and handle the errors anywhere it occurs, just remove the blocks from the called ones.
    ALTER PROCEDURE "sp_staging" @denominator FLOAT
    AS
    DECLARE @quotient FLOAT;
    SET @denominator=1/@denominator;
    INSERT INTO T1 VALUES('sp_staging finished');
    GO
    ALTER PROCEDURE "sp_upload" @denominator FLOAT
    AS
    DECLARE @quotient FLOAT;
    SET @denominator=1/@denominator;
    INSERT INTO T1 VALUES('sp_upload finished');
    GO
    ALTER PROCEDURE "sp_process" @denominator FLOAT
    AS
    DECLARE @quotient FLOAT;
    SET @denominator=1/@denominator;
    INSERT INTO T1 VALUES('sp_process finished');
    GO
    ALTER PROCEDURE "sp_daily" @p1Deno FLOAT,@p2Deno FLOAT,@p3Deno FLOAT
    AS
    BEGIN TRY
    EXEC sp_staging @p1Deno;
    EXEC sp_upload @p2Deno;
    EXEC sp_process @p3Deno;
    END TRY
    BEGIN CATCH
    INSERT INTO T1 SELECT ERROR_MESSAGE();
    END CATCH
    GO
    --Test Example
    TRUNCATE TABLE T1;
    EXEC sp_daily 1,0,1;
    SELECT * FROM T1;
    As we can see from the above modification,  sp_daily calls  sp_staging, sp_upload, sp_process in order. Sp_staging runs fine so it finishes. When it comes to sp_upload, error gets captured so the execution terminates. Anyway if you hope that the 3
    called procedures  work atomically(it is a pretty common business requirement), which means unless all of the three finish otherwise no one finishes, the TRAN block would help. Please see the below code.
    ALTER PROCEDURE "sp_daily" @p1Deno FLOAT,@p2Deno FLOAT,@p3Deno FLOAT
    AS
    BEGIN TRY
    BEGIN TRAN
    EXEC sp_staging @p1Deno;
    EXEC sp_upload @p2Deno;
    EXEC sp_process @p3Deno;
    COMMIT TRAN;
    END TRY
    BEGIN CATCH
    ROLLBACK TRAN;
    INSERT INTO T1 SELECT ERROR_MESSAGE();
    END CATCH
    GO
    --Test Example
    TRUNCATE TABLE T1;
    EXEC sp_daily 1,0,1;
    SELECT * FROM T1;
    If you have question, feel free to let me know.
    Best Regards,
    Eric Zhang

  • Multiple catch for try -Exception Already caught Running smoothly..

    take this code for example...
    This one runs smoothly..
    public class one
         public static void main(String args[])
              int i=27;
              try
                   System.out.println(i/0);
              catch(ArrayIndexOutOfBoundsException e)
                   System.out.println(e);
              catch(Exception e)
                   System.out.println(e);
    }However if i change the order it would give me a compile time error which in my sun sl-275 book is written it should run fine.
    "If the Exception Catch clause is put first, then it would handle all exceptions, and the MyException or MyOtherException catch clauses would never be invoked."
    which i think is wrong because the code never gets compiled...
    public class one
         public static void main(String args[])
              int i=27;
              try
                   System.out.println(i/0);
              catch(Exception e)
                   System.out.println(e);
              catch(ArrayIndexOutOfBoundsException e)
                   System.out.println(e);
         }please discuss.

    DogsAreBarking wrote:
    take this code for example...
    This one runs smoothly..
    public class one
         public static void main(String args[])
              int i=27;
              try
                   System.out.println(i/0);
              catch(ArrayIndexOutOfBoundsException e)
                   System.out.println(e);
              catch(Exception e)
                   System.out.println(e);
    }However if i change the order it would give me a compile time error Correct. Each exception can be caught only once, Catching an exception implicitly catches every subclass exception of the one caught.
    In the first example, the code is fine, because your first catch block will catch only ArrayIndexOutOfBoundsException, and the second catch block will catch anything that was not caught previously--in other words, everything other than ArrayIndexOutOfBoundsException (and any child classes it may have).
    In the second example, the first catch block handles Exception and all of its subclasses, so catching ArrayIndexOutOfBoundsException is wrong.

  • Error in Raising exceptions in a method and handling the same in the WF

    Hi All
    I tried to implement Raising exceptions in a method and handling the same in the workflow
    in the same way given in SAPtechnical site .
    1.by adding a error msg in exception parameter .
    2. if the select query fails, to fetch the agent then :exit_return 9001 'ztable name' space space space.
    3.in the Background activity in which this method is called there automatically one outcome appears ,and I hav acitvated that outcome and in that done what need to be done for that error handling - just send a mail to concern person .
    4. in the normal outcome of the activity , the step to be executed are there .
    but its not working , if exception come then the WF stuck there only . it do not follow the exception outcome .
    Kindly help me , How can I do the exception handly in WF.
    thanks & Regards
    Kakoli

    > That is usually the case - you catch an error in the underlying program and pass that back so the workflow can go into error.
    > You're doing it correctly.
    I don't think that's quite right.
    If you define an error/exception in a method, it is automatically mapped to an outcome of the step/task.
    If you activate that outcome, then you can handle the exception in a branch of the workflow.
    For example: 'Remote connection is down, please contact Basis'
    The step should only go into error if an outcome occurs that you have NOT activated.
    So the original question is valid. Please give some more information on what the error message is..
    chrs
    Paul

  • Some basic questions how to handle Exceptions with good style

    Ok I have two really basic Exception questions at once:
    1. Until now I always threw all exceptions back all the way to my main method and it always worked well for me but now I am sitting at a big project where this method would explode the programm with throwings of very many exceptions in very many methods. So I would like to know if there is a more elegant solution.
    2. What do I do with exceptions that will never occur?
    Lets say I have a method like this:
    void main() {calculate();}
    void calculate()
    sum(3,5);
    void sum(int a,int b)
    MathematicsA.initialise("SUM"); // throws AlgorithmNotFoundException, will never occur but has to be handled
    }So what is the most elegant way?:
    h4. 1. Ignore because it will not happen
    void sum(int a,int b)
    try {MathematicsA.initialise("SUM");}
    catch(AlgorithmNotFoundException) {}
    }h4. 2. Print stacktrace and exit
    void sum(int a,int b)
    try {MathematicsA.initialise("SUM");}
    catch(AlgorithmNotFoundException e)
    e.printStackTrace();
    System.exit();
    }h4. 3. throw it everywhere
    void main() throws AlgorithmNotFoundException, throws ThousandsOfOtherExceptions  {}
    void calculate()  throws AlgorithmNotFoundException, throws HundretsOfOtherExceptions
    sum(3,5);
    void sum(int a,int b) throws AlgorithmNotFoundException
    MathematicsA.initialise("SUM");
    }h4. 4. Create special exceptions for every stage
    void main() throws MainParametersWrongException
    try {calculate();}
    catch(Exception e)
      throw new MainParametersWrongException();
    void calculate()  throws SumInternalErrorException
    try {sum(3,5);}
    catch (SumInternalErrorException)    {throw new CalculateException();}
    void sum(int a,int b) throws SumInternalErrorException
    try
    MathematicsA.initialise("SUM");
    } catch (AlgorithmNotFoundException e) {
    throw new SumInternalErrorException();
    }P.S.: Another problem for me is when a method called in a constructor causes an Exception. I don't want to do try/catch everytime I instantiate an object..
    Example:
    public class MySummation()
         Mathematics mathematics;
         public MySummation()
                 mathematics.initialise("SUM"); // throws AlgorithmNotFoundException
         void sum(int x,int y)
              return mathematics.doIt(x,y);
    }(sorry for editing all the time, I was not really sure what I really wanted to ask until i realised that I had in fact 2 questions at the same time, and still it is hard to explain what I really want to say with it but now the post is relatively final and I will only add small things)
    Edited by: kirdie on Jul 7, 2008 2:21 AM
    Edited by: kirdie on Jul 7, 2008 2:25 AM
    Edited by: kirdie on Jul 7, 2008 2:33 AM
    Edited by: kirdie on Jul 7, 2008 2:34 AM

    sphinks wrote:
    I`m not a guru, but give my point of view. First of all, the first way is rude. You shouldn`t use try with empty catch. "rude" isn't the word I'd use to describe it. Think about what happens if an exception is thrown. How will you know? Your app fails, and you have NO indication as to why. "stupid" or "suicidal" are better descriptions.
    Then for the second way, I`ll reccomend for you use not printStackTrace(); , but use special method for it:
    public void outputError (Exception e) {
    e.printStackTrace();
    }It`ll be better just because if in future you`d like to output error message instead of stack of print it on GUI, you`ll need change only one method, but not all 'try' 'catch' statements for changing e.printStackTrace(); with the call of new output method.I disagree with this. Far be it from me to argue against the DRY principle, but I wouldn't code it this way.
    I would not recommend exiting from a catch block like that. It's not a strategy for recovery. Just throw the exception.
    Then, the third way also good, but I suppose you should use throws only if the caller method should know that called method have a problem (for example, when you read parametrs from gui, so if params are inccorect, main method of programm should know about it and for example show alert window)."throw it everywhere"? No, throw it until you get to an appropriate handler.
    If you're writing layered applications - and you should be - you want to identify the layer that will handle the exception. For example, if I'm writing a web app with a view layer, a service layer, and a persistence layer, and there's a problem in the persistence tier, I'd let the service layer know what the persistence exception was. The service layer might translate that into some other exception with some business meaning. The view layer would translate the business exception into something that would be actionable by the user.
    And in all other cases I suppose you should use the fourth way. So I suppose it`s better to combine 2,3,4 ways as I have mentioned above.I don't know that I'd recommend special exceptions for every layer. I'd reuse existing classes where I could (e.g., IllegalArgumentException)
    Sorry, I can give you advice how to avoid problem with try-catch in constructor. :-(You shouldn't catch anything that you can't handle. If an exception occurs in a constructor that will compromise the object you're trying to create, by all means just throw the exception. No try/catch needed.
    You sound like you're looking for a single cookie cutter approach. I'd recommend thinking instead.
    %

  • Get Attribute values from a page and procedure exception handling?

    Hi All,
    I have created new page with two input attributes not based on any VO. This page is created to capture two values and pass these to an AM method upon pressing OK button. The method in AM will call a procedure with two in parameter expecting the two values captured from the above said page.
    I have two questions, first one how to capture the values entered by the page in the controller class and advises me how to handle exceptions when my procedure fails.
    I can not use something like this since this page is not based on a VO
    String fromName = (String)vo.getCurrentRow().getAttribute("FromName");
    Do I have to create a dummy VO like select '' name1, '' name2 from dual?
    Thanks for the help.

    Hi,
    Actually you can capture the parameters on the page like this way
    String test = (String)pageContext.getParameter("id of the text input bean");
    Now in procedure you can take an out parameter which stores the error messages on exception
    and return that out parameter in java.
    and then you can throw exception on page using OAException class.
    Thanks
    Gaurav Sharma

  • Handling servlet and io  exceptions

    hello
    i am developing a web application consists of a number of servlets!, i want to forward the request to an error page if a servlet or io exception occurs, one method i can figure out is, surrounding the stetments of doGet and doPost methods in a try-catch block! and redirect in the catch block. however i dont want to re-edit my servlets...
    is there a solution that automatically forwards servlet and io exceptions of doGet or doPost methods
    thanks in advace

    In your web.xml you can declare exceptions to be caught:<!ELEMENT error-page ((error-code | exception-type), location)>I've never used this but according to the API spec it should give you your error handling.
    Anthony

  • Need help. I am running a 27 in imac with 16 gigs of ram. Photoshop runs really fast, except when opening files. It takes 5-10 minutes to open even a small file of 1 meg. I cleaned and validated all the fonts and removed all questionable fonts. Reset pref

    Need help. I am running a 27 in imac with 16 gigs of ram. Photoshop runs really fast, except when opening files. It takes 5-10 minutes to open even a small file of 1 meg. I cleaned and validated all the fonts and removed all questionable fonts. Reset preferences and still have problem. Slow to open and in force quit "Photoshop not responding" At this point should I uninstall and start over.

    What are the performance Preferences?

  • Throw exception in Java mapping and handle this in BPM

    Hi,
    I'll use a Java mapping in a BPM transform step. Is it possible to throw an exception inside this Java mapping and handle this in a BPM exception handler?
    thanks and regards
    Verena

    Hi Verena,
    In a BPM transformation step, I think you can throw exceptions only for system errors.
    Let me explain with an example, one of the ways to handle your scenario:
    Lets assume your Java Mapping fails then you can trap that exception in your Java mapping and compose an XML message which indicates that an error has occurred.
    say for e.g.
    <intermediateStructure>
    <SatusDocument>
    <StatusCode>ERROR</StatusCode>
    <ErrCode>123</ErrCode>
    <ErrDesc><!populate the thrown exception details></ErrDesc>
    </StatusDocument>
    <Payload>
    <!contains actual XML message with data>
    </Payload>
    </intermediateStructure>
    if Java mapping is Successful, you can compose the XML message as follows:
    <intermediateStructure>
    <SatusDocument>
    <StatusCode>SUCCESS</StatusCode>
    <ErrCode>0</ErrCode>
    <ErrDesc></ErrDesc>
    </StatusDocument>
    <Payload>
    <!contains actual XML message with data>
    </Payload>
    </intermediateStructure>
    You can use BPM switch operation to switch to different processing branches say for e.g. "error" branch or "success" branch by examining the value of <StatusCode> tag.
    Hope it helps !
    Regards,
    Sridhar

  • Biztalk 2010 handling exception using the scope in Orchestration.

    Hello,
    1. I am trying to handle the errors and put them in the log using Scope. Here is the Orchestration I used,
    The Expression_1 has
    System.Diagnostics.EventLog.WriteEntry("Message Sent to the destination", "Message Sent to the destination");
    Expression_2 has
    System.Diagnostics.EventLog.WriteEntry("Failed to send the message to destination", "Failed to send the message to destination --" + exception.ToString() );
    Expression_3 has
    System.Diagnostics.EventLog.WriteEntry("General Exception-- Failed to send the message to destination", "Caught GeneralException-- Failed to send the message to destination");
    When the message is sent without errors it shows up in the log. The message with error doesnot show up I dont know why,
    I don't know what has to be changed.
    2. I also don't know how to construct the error message and send it through email without using ESB toolkit. Any help is greatly appreciated. Thanks

    Not sure I understand your first question. Is it "how to create and test an error (hence an error handling)?" If so, the easiest way is to add an Throw exception shape and set up the exception you are going to catch in the exception catch block.
    2. you can use just the plain C# code like this:
    MailMessage mail = new MailMessage("[email protected]", "[email protected]");
    SmtpClient client = new SmtpClient();
    client.Port = 25;
    client.DeliveryMethod = SmtpDeliveryMethod.Network;
    client.UseDefaultCredentials = false;
    client.Host = "smtp.google.com";
    mail.Subject = "this is a test email.";
    mail.Body = "this is my test email body";
    client.Send(mail);
    copied from
    here. It uses
    System.Net.SmtpClient class.
    Leonid Ganeline [BizTalk MVP] <a href="http://social.technet.microsoft.com/wiki/contents/articles/20258.biztalk-integration-development-architecture.aspx">BizTalk Development Architecture</a>

  • Handling exceptions generated by invkoe

    hi!
    i have the next problem, i use invoke to call a method in the class of a certain object, but i don't know how handle the exepctions dispatched by this method
    my code is like thisClass[] tiposParametros = {Clase.getClass()};
    try {
         java.lang.reflect.Method metodo = objeto.getClass().getMethod("metodo", tiposParametros);
         Object[] parametros = Clase.getParametros();
         regreso = (Object[])metodo.invoke(objeto, parametros); // this method has its own exceptions
    } catch (Exception e) {
         // exceptions like IllegalAccesException, IllegalArgumentException,..
    } catch (OtherException ex) {
         // Here i have an "unreachable catch"
    }any advice on as I can you handle my own exceptions?
    regards

    Okay, it sounds like you need a little firmer background on exceptions in Java. Here's as brief a rundown as I can give you and still cover the major points.
    First, there is a class hierarchy.
    Throwable
        |
        +--Error
        |    | ...  (subclasses of Error)
        |
        +--Exception
              |
              +--RuntimeException
              |      +
              |      |
              |      +--ClassCastException
              |      |
              |      +--NullPointerException
              |      | ...
              |
              +--InvocationTargetException
              |
              +--YourExceptions
              | ...
    Error and its subclasses, and RuntimeException and its subclasses are called "unchecked exceptions." Everything is a "checked exception".
    Whenever a checked exception can thrown during the execution of a method, that method must either catch the checked exception, or declare "throws ExceptionName" in the method declaration. This is done so that callers of the method no that the method cannot throw any checked excpetions other than those listed. If I'm calling a method, that means I know exactly which kind of exceptions I need to deal with. As long as I handle those, nothing else will get by me. If you don't follow this rule, you get a "must be caught or declared to be thrown" error at compile time.
    For unchecked excpetions (Error, RuntimeException) there is no such requirement. You can throw an unchecked exception without explicitly stating so. The reason is this: Errors are internal VM problems that you can't do anything about anyway (OutOfMemory, etc.), and if things get bad enough to throw an Error, chances are that the state of the VM is such that just exiting immediately is the best course of action. RuntimeExceptions, on the other hand, occur because of a programmer error, and could have been prevented. For example, you can always prevent NullPointerException by doing an explicit check for null anywhere  that it could occur and cause a problem.
    The checked exceptions are the ones that you can't really prevent just with good coding practices, so you have to find a way to deal with them: Disk filling up, socket closing unexpectedly, etc.
    One final point: when you say "throws SomeException", that means you're allowed to throw that exception and any of its descendant classes. When you say "catch (SomeException e)", you'll catch that class and any of its descendant classes (unless a prior catch block named a more specific class that ends up matching).
    Armed with that knowledge, lets look at your problems:
    hi again jeff!
    i try your suggestions(1,2,3), but i have the next
    error messages:
    1. unreported exception: java.lang.Throwable; must be
    caught or declared to be thrown} catch (java.lang.reflect.InvocationTargetException
    ex) {
    try {
    throw ex.getTargetException();
    } catch (ExceptionCon e1) {
    System.out.println("con");
    } catch (ExceptionVac es) {
    System.out.println("vac");
    This is the "catch it or declare it" rule. Since ex.getTargetException returns a Throwable, it could be anything in the entire exception hierarchy--checked or unchecked--as far as the compiler knows. We've only handled two checked exceptions. We need to either:
    1) change our throw statement to throw something no higher up the heirarchy than what we're catching
    or
    2) change or add to our catch block to make sure that if what we've just thrown isn't one of the two excptions we named, we still handle it. Kind of like a "default" in a case statement.
    2. i cant't get the class from my Exception, i don't
    know why; identifier required, but package found
    I have no idea what you're saying here.
    3. i recibe this message; method
    procesaExcepcion(java.lang.Throwable) not found; in i
    have declared that method like: void procesaExcepcion(ExcepcionCon e) {
    Remember, getTargetException gives us a Throwable, which is an ancestor class of ExcepcionCon. Even if we know that at runtime it can only be ExcepcionCon, the compiler doesn't know that. As far as the compiler knows, it could be anything. So we're calling processExcepcion with a Throwable, but we don't have prcoessException(Throwable).
    Actually, I apologize. Now that I think about it, this way won't work. I got confused and tried to do "reverse polymorphism (TM)" again. Forget I even mentioned this way. A similar approach is doable with reflection, but it's fairly complex, and you end up possibly throwing another InvocationTargetException.
    Anyway, why don't you chew on that first problem for a while, and if you get stuck or have more specific questions, post again.

  • 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.

Maybe you are looking for