Exception handling in static block

How to handle and exception raised in static block, pls answer

Yeah, you are right, but I was just quoting the example on how to use it.
Now, come to your problem,
1. Static blocks are executed first time, when a class is loaded, i.e. when first reference of class is made.
2. So, handle the situation there.
E.g.
You have test class:
public class Test {
     static{
          try{
               String s = null;
               File f = new File(s);
          }catch(Throwable ne)
               System.out.println("Eror");
               throw new RuntimeException(); // Or use Error depends on your implementation
     public static void abc(){
          System.out.println("Hello");
Now,
calling it from another class:
public class Test1 {
     public static void main(String[] args) {
          try{
          Test.abc(); *// This is the first instance where class for Test will be load and hence the static block will be executed*
          }catch(Throwable th) // Or catch Error
               th.printStackTrace(); // Do the handling
          System.out.println("Done");
This is a standard practice. From static block, instead of throwing Error exception, use some of your inherited class from Error. (i.e. create a exception framework inside your application)
Hope this explains my point.

Similar Messages

  • Error handling in static block

    Hello All,
    I have the following code
    static{
    abc();
    private static void abc() throws Exception{
    how do I throw error in static block because if I write
    static {
    abc() throws Exception;
    it gives error during compilation.
    How do I handle it.
    Sachin

    This is my code ...
    import java.io.FileInputStream;
    import java.io.*;
    import java.util.Properties;
    * @author sachin
    * This class is used setting the configurations
    public class Config{
         static String files_incoming;
         static String files_outgoing;
         static{
              try {
                   configurations();
              } catch (ICMSException e) {
                   LoggerCitiUtil.debug("Error in static block");               
         public static void configurations() throws ICMSException{
              Properties prop = new Properties();
              try{
                   Properties property = System.getProperties();
                   String systemPath = property.getProperty("MAIN_BASE_PATH");
              prop.load(new FileInputStream( systemPath + "bin/scp.ini"));
              }catch(IOException e){                 
                   LoggerCitiUtil.debug("File not loaded in Config class");               
              try{
    files_incoming=prop.getProperty("files_incoming").trim();;
    files_outgoing=prop.getProperty("files_outgoing").trim();;                                   
              }catch(Exception e){
                   LoggerCitiUtil.debug("Error in Config class");
                   e.printStackTrace();
    In the static block I want to throw new ICMSException(e);
    When I write this :
         static{
              try {
                   configurations();
              } catch (ICMSException e) {
    throw new ICMSException(e);
                   LoggerCitiUtil.debug("Error in static block");               
    But it gives unhandled Exception during compile time.
    Can anyone help me out ?.

  • Exception-handling in a block (integration process)

    Hi,
    I have created an error handling in a block, but I want to send the information of the exception from xi to our software clix that is connected to xi via jms adapter.
    Is it possible??
    I'm new in XI, so can you give my a detailed hint?
    Thanks for your reply.
    Regards
    Stefan

    hi,
    >>>but I want to send the information of the exception from
    yes and no:)
    you cannot send an error message (cause there's no way how to map it)
    but you can send a standard text like "error"
    how to do that?:
    inside the exception branch
    add a transformation step in which you define dummy
    transformation which only fills one line "error"
    to the target message
    then you can add a send step (remember you're still inside the exception branch) and send this error message...
    Regards,
    michal

  • Handling loop exception in an anonymous block

    hI ,
    I have a an anonymous block
    declare
    cursor
    local variables
    begin
    open cursor
    some statements
    loop
    some statement ;
    some othet statement;
    select something from sometablein local variable where some field = cursor.value ;
    some more statements
    end loop
    some more statements
    exception
    when whatever
    then whatever
    end;
    Now my select statement may give a NO_DATA_FOUND error which i want to catch and ignore .
    Pls tell me how to do it.

    So that mean you can have multiple exception blocks
    in a pl/sql script ?You can have one exception handler per execution block.
    Execution blocks can be nested inside other execution blocks.
    Handling the error within one exception handler causes execution to return out to the execution of the parent block.
    Raising an error within one exception handler causes the execution to go straight to the exception handler of the parent block.
    e.g.
    -- execution block 1
    BEGIN
      -- execution block 2
      DECLARE
        myvar number;
      BEGIN
        SELECT mynumber INTO myvar FROM mytable;
      EXCEPTION
        WHEN NO_DATA_FOUND THEN
          NULL;  -- handle error and return execution to block 1
        WHEN OTHERS THEN
          RAISE; -- raise any other errors to block 1 exception handler
      END; -- block 2
      DBMS_OUTPUT.PUT_LINE('Select took place successfully or no data was found');
    EXCEPTION
      WHEN OTHERS THEN
        DBMS_OUTPUT.PUT_LINE('An error occurred either in block1 or in block 2 (except for NO_DATA_FOUND in block2)');
    END;

  • Exception in static block + re-instantiating

    Hello All,
    I have got a number of unit tests and one that is running is causing an exception in a static block of a class which is expected. It throws an ExceptionInInitializerError which I catch in the unit test.
    But then another test is running using the same class and this time it should pass and create an instance of the same class as before.
    But instead I receive a java.lang.NoClassDefFoundError with no class name. Why? Can't I instantiate a class again once the initialisation had failed?
    Regards
    Jonas

    It's part of the VM Specification.
    See [2.17.5 Detailed Initialization Procedure|http://java.sun.com/docs/books/jvms/second_edition/html/Concepts.doc.html#24237]
    The first time,
    10. Otherwise, the initializers must have completed abruptly by throwing some exception E. If the class of E is not Error or one of its subclasses, then create a new instance of the class ExceptionInInitializerError, with E as the argument, and use this object in place of E in the following step. But if a new instance of ExceptionInInitializerError cannot be created because an OutOfMemoryError occurs, then instead use an OutOfMemoryError object in place of E in the following step.After that,
    5. If the Class object is in an erroneous state, then initialization is not possible. Release the lock on the Class object and throw a NoClassDefFoundError.

  • Exception handling of Transport acknowledgement in asynchronous send in BPM

    HI,
    A silly question, but your help would be greatly appreciated..
    - I have a asynch send step in a BPM for sending data to the target system through RFC
    - It has acknoweledgement property of this send step is set to transport acknowledgement
    - The exception property of this send step is set to throw a 'RFCException'
    - This send step is inside a block
    - This block also has an Exception branch which catches this 'RFCException'
    - now my RFC channel failed for some known reason, but the flow never went into the Exception branch
    IS this behaviour of the 'transport acknowledgement' property of an asynch send step in BPM expected ?
    What should I take care so that if my RFC receiver channel throws an exception, the flow of my BPM goes to the exception branch ??

    - now my RFC channel failed for some known reason, but the flow never went into the Exception branch
    IS this behaviour of the 'transport acknowledgement' property of an asynch send step in BPM expected ?
    What should I take care so that if my RFC receiver channel throws an exception, the flow of my BPM goes to the exception
    branch ??
    When an exception is caught by the Transport Acknowledgement it will trigger the Exception branch (if the send step is defined inside a Block with an Exception Branch)
    I think you have not defined (and then assigned) a proper Exception Handler for the Block.
    Click on the Block and define an Exception Handler......click on the Exception Branch and then select the Exception Handler from the dropdown......if this is not done then the Exception Branch wont be executed.....perform a check on your BPM in IR (using F7) you may get some warnings.
    Regards,
    Abhishek.

  • Exception Handling In BPEL  By using Catch Blocks or Fault Policies Or Both

    I have a confusion regarding
    Exception handling :
    When Should i go for 1)Catch Block (Remote , or binding ) in bpel for exception handling .
    2)Fault Policy , Fault binding.xml
    Currently iam using catch blocks , but even fault policy is good , but can i use both...
    Currently in My bpel ,when any error occurs i have to send a error notification by Email .
    Currently i have exposed the email service which shuts emails and write a file with errored Message.
    Hence if any error i will catch i in a parent BPEL, i will just invoke the above email, service .
    So anybody can help me by giving the suggestion how to go for the best approach
    Edited by: anantwag on Mar 23, 2011 6:31 AM

    Currently in My bpel ,when any error occurs i have to send a error notification by Email .
    Currently i have exposed the email service which shuts emails and write a file with errored Message.Seeing your use case I will suggest you to use fault handling framework (fault policy). Fault handling framework should be used where you need generic error handling framework which handles all the faults occured in any composite component. Generally BPEL catch block should be used to propagate error info/fault back to the client/to fault handling framework or to consume an error
    Regards,
    Anuj

  • Use of raise in exception handling block

    what is the use of raise in exception handling block for eg.
    declare
    a number;
    b emp.empno%type;
    begin
    begin
    SELECT empno INTO a FROM emp where 1=2;
    exception
    when others then
    dbms_output.put_line('inner');
    raise;
    end;
    exception
    when no_data_found then
    dbms_output.put_line('outer');
    end;
    output will be like below ..
    inner
    outer
    PL/SQL procedure successfully completed.
    my question is wht is the use of using raise in exception handing part, is there any specific reason we use in the development ????
    Regards,
    AAK.

    In the first block, you do not raise you user-defined exception WHEN_NO_DATA_FOUND, but the predefined one, which is raised to the WHEN OTHERS exception handler.
    Consider:
    SQL> declare
      2     a number;
      3     my_err exception;
      4     no_data_found exception;
      5  begin
      6     begin
      7        select 1 into a from dual where 1=2;
      8     exception
      9     when no_data_found then
    10        dbms_output.put_line(' In system defined');
    11        raise my_err;
    12     end;
    13  exception
    14     when my_err then
    15        dbms_output.put_line('In User Defined');
    16     when others then
    17        declare
    18           v_sqlerrm varchar2(100);
    19        begin
    20           v_sqlerrm := sqlerrm;
    21        dbms_output.put_line(' In when others '||sqlerrm);
    22        end;
    23  end;
    24  /
    In when others ORA-01403: no data found
    PL/SQL procedure successfully completed.
    SQL> ed
    Wrote file afiedt.buf
      1  declare
      2     a number;
      3     my_err exception;
      4     --no_data_found exception;
      5  begin
      6     begin
      7        select 1 into a from dual where 1=2;
      8     exception
      9     when no_data_found then
    10        dbms_output.put_line(' In system defined');
    11        raise my_err;
    12     end;
    13  exception
    14     when my_err then
    15        dbms_output.put_line('In User Defined');
    16     when others then
    17        declare
    18           v_sqlerrm varchar2(100);
    19        begin
    20           v_sqlerrm := sqlerrm;
    21        dbms_output.put_line(' In when others '||sqlerrm);
    22        end;
    23* end;
    SQL> /
    In system defined
    In User Defined
    PL/SQL procedure successfully completed.
    SQL>Note that in the second block, I deleted the declaration of the user defined exception NO_DATA_FOUND.
    This is taken from the documentation:
    Redeclaring Predefined Exceptions
    Remember, PL/SQL declares predefined exceptions globally in package STANDARD, so you need not declare them yourself. Redeclaring predefined exceptions is error prone because your local declaration overrides the global declaration. For example, if you declare an exception named invalid_number and then PL/SQL raises the predefined exception INVALID_NUMBER internally, a handler written for INVALID_NUMBER will not catch the internal exception. In such cases, you must use dot notation to specify the predefined exception, as follows:
    EXCEPTION
      WHEN invalid_number OR STANDARD.INVALID_NUMBER THEN
        -- handle the error
    END;You can read yourself :
    http://download-uk.oracle.com/docs/cd/B19306_01/appdev.102/b14261/errors.htm
    Regards,
    Gerd

  • Implementing Exception Handling Application Block in custom web parts, event receivers

    hi,
      I am currently implementing try {} catch(Exception expp) { throw expp;} to handle exceptions in my intranet appln.
    I have several custom web parts, event receivers, few console applciations as timer jobs etc. If i want to implement a  robust exception handling what should be  the approach. by searching, i saw, ms patterns n practices provides the
    appln blocks.
    But I think[ pls correct me if i am wrong ] those  appln blocks are meant for asp.net applns ONLY.
    if not, anyone has implemented those appln blocks in SP development? if yes, can anyone provide one sample /  link to implement Exception Handling in SP.
    help is appreciated! 

    Hi,
    Here are some articles for your reference:
    Handling Error Centrally in a SharePoint Application
    http://www.codeproject.com/Articles/26236/Handling-Error-Centrally-in-a-SharePoint-Applicati
    Using Microsoft Enterprise Library Application Block in SharePoint
    http://www.codeproject.com/Articles/21389/Using-Microsoft-Enterprise-Library-Application-Blo
    Exception Handling in SharePoint
    http://spmatt.wordpress.com/2012/02/01/exception-handling-in-sharepoint/
    Best Regards
    Dennis Guo
    TechNet Community Support

  • Exception handling for Scanner console input

    I'm trying to add exception handling to a Scanner console to deal with exceptions caused by non-numeric input. My idea was to do use a try/catch in a for loop and break if no exception occurs.
    Whats happening is the "iNumber = console.nextInt(); " does nothing on subsequent retries, when an exception occurs. That is, I enter "123w", an InputMismatchException occurs, goes into the first catch block, hits "continue" and goes back into the for loop, hits the "iNumber = console.nextInt(); ", then immediately blows through it without executing. Thus, I hit my max loop count and exit with iNumber = 0.
    I'm thinking I may need to instantiate "static Scanner console = new Scanner(System.in);" again in the event of an exception?
    Thanks for any feedback. I'm brand new at Java and learning as fast as I can :)
    Here is the code:
    class ConsoleInput
         public ConsoleInput() // constructor
         static Scanner console = new Scanner(System.in);
         public int GetInput()
              int iNumber = 0;
              for(int i=0; i<3; i++)
              try
                   System.out.print("Please enter a number: ");
                   iNumber = console.nextInt(); // get console input
                   break;
              catch(java.util.InputMismatchException ex)
                   continue;
              catch(Exception ex)
                   continue;
         return iNumber;
    }

    public class Scratch {
      public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        boolean gotAValidInt = false;
        int theInt;
        System.out.println("Enter an int");
        do {
          try {
            theInt = sc.nextInt();
            gotAValidInt = true;
          catch (InputMismatchException exc) {
            System.out.println("Not an int. Try again.");
            sc.next(); // consume the non-int that nextInt couldn't consume
        } while (!gotAValidInt);
    }There are different ways you could structure your loop, but the key is that when nextInt throws an exception, you have to call next() in the catch block to consume the token that nextInt couldn't.
    Edited by: jverd on May 2, 2008 1:52 PM

  • Removing Exception Handling Causes Compiler Error

    I am very new to Java. I have a background in other programming languages including Ruby. I am in need of a convenient means to parse XML code. I picked up the code shown at the end of this message on the Internet. In its original form, it works perfectly. I experimented by trying to comment out the try block as you can see. I was surprised to find that in that form it wouldn't compile. In essence, I thought what I was doing was simply removing exception handling. I figured that since the code worked and there were no exceptions being thrown, it would work just fine for experimentation purposes. (I understand that I would not want to do this in production mode.) Can someone please explain to me why removing the exception handling causes the program to fail to compile?
    Thanks for any input.
    ... doug
    /* Experimental Code */
    /* http://www.mkyong.com/java/how-to-read-xml-file-in-java-dom-parser/ */
    import javax.xml.parsers.DocumentBuilderFactory;
    import javax.xml.parsers.DocumentBuilder;
    import org.w3c.dom.Document;
    import org.w3c.dom.NodeList;
    import org.w3c.dom.Node;
    import org.w3c.dom.Element;
    import java.io.File;
    public class ReadXMLFile {
    public static void main(String argv[]) {
    try {
    File fXmlFile = new File("ReadXMLFile.xml");
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    Document doc = dBuilder.parse(fXmlFile);
    doc.getDocumentElement().normalize();
    System.out.println("Root element :" + doc.getDocumentElement().getNodeName());
    NodeList nList = doc.getElementsByTagName("staff");
    System.out.println("-----------------------");
    for (int temp = 0; temp < nList.getLength(); temp++) {
    Node nNode = nList.item(temp);     
    if (nNode.getNodeType() == Node.ELEMENT_NODE) {
    Element eElement = (Element) nNode;
    System.out.println("First Name : " + getTagValue("firstname",eElement));
    System.out.println("Last Name : " + getTagValue("lastname",eElement));
    System.out.println("Nick Name : " + getTagValue("nickname",eElement));
    System.out.println("Salary : " + getTagValue("salary",eElement));
    } catch (Exception e) {
    e.printStackTrace();
    private static String getTagValue(String sTag, Element eElement){
    NodeList nlList= eElement.getElementsByTagName(sTag).item(0).getChildNodes();
    Node nValue = (Node) nlList.item(0);
    return nValue.getNodeValue();
    }

    877757 wrote:
    I figured that since the code worked and there were no exceptions being thrown, it would work just fine for experimentation purposes. The compiler doesn't know that your code works. It only knows that some method you call can throw some checked exception, and it requires you to catch it or declare that you don't.

  • Can we have try/catch in a static block in a class?

    hi All
    i have a question about put a try/catch block in a static block in a class to catch exceptions that maybe thrown from using System.xxxx(). in my custom class, i have a static block to initialize some variables using System.xxx(). in case of any error/exception, i need to be able to catch it and let the caller know about it. i tried to put a try/catch block in the static block, and tried to rethrow the exception. but it is not allowed, how would i handle situation like this? thanks for your help and advise in advance.

    You could just swallow the exception inside try/catch
    block, and instead of throwing it out, just set a
    static variable to allow checking from outside
    whether the initialization succeeded, or check within
    the constructor / methods of this class for
    successful initialization, and throw the exception
    then. You could even save that exception in a static
    variable for later.Ouch, ouch, you're hurting my brain. This would allow someone to ignore a (presumably) fatal error. Throw a RuntimeException as indicated. You can wrap a checked exception in an unchecked one if need be.

  • Exception Handling related problem

    Can anybody tell me why it is not giving ArithmeticException.
    package pckg1;
    * @author anil_saini
    * TODO To change the template for this generated type comment go to
    * Window - Preferences - Java - Code Style - Code Templates
    import java.io.FileNotFoundException;
    public class Average7 {
         public static void main(String[] args) throws InterruptedException,FileNotFoundException {
         try {                                                      // (1)            System.out.println(printAverage(100, 0));                                  // (2)
         } catch (ArithmeticException ae) {                         // (3)
         Thread.sleep(1000);
              ae.printStackTrace(); // (4)
    System.out.println("Exception handled in " + // (5)
         "main().");
         finally {
         System.out.println("Finally in main()."); // (6)
         System.out.println("Exit main()."); // (7)
    public static int printAverage(int totalSum, int totalNumber) {
         int average=0;
         try {                                                      // (8)
    average = computeAverage(totalSum, totalNumber); // (9)
         System.out.println("Average = " + // (10)
         totalSum + " / " + totalNumber + " = " + average);
         return average;
         } catch (IllegalArgumentException iae) {                   // (11)
              iae.printStackTrace(); // (12)
    System.out.println("Exception handled in " + // (13)
         "printAverage().");
         } finally {
    System.out.println("Finally in printAverage()."); // (14)
         return average;
         }     // (15)
    public static int computeAverage(int sum, int number) {
         System.out.println("Computing average.");
         if (number == 0) // (16)
    throw new ArithmeticException("Integer division by 0");// (17)
         return sum/number; // (18)
    Output
    =======================
    Computing average.
    Finally in printAverage().
    0
    Finally in main().
    Exit main().

    Because return statements in finally blocks are evil!
    int average = 0;
    try
    { // (8)
         average = computeAverage(totalSum, totalNumber); // (9)
         System.out.println("Average = " + // (10)
                   totalSum + " / " + totalNumber + " = " + average);
         return average;
    catch (IllegalArgumentException iae)
    { // (11)
         iae.printStackTrace(); // (12)
         System.out.println("Exception handled in " + // (13)
                   "printAverage().");
         throw new IllegalArgumentException();
    finally
         System.out.println("Finally in printAverage()."); // (14)
         return average; // (15)
    }You get an exception at (9), but finally is guaranteed to be executed, so the JVM executes it. Now you return in your finally block (15), and the JVM is left with the choice of executing your return statement or propagating the exception. Since, as said, finally is guaranteed to be executed, it returns and swallows the exception.
    That's why IMHO return statements in finally blocks should not be allowed.
    (Some compilers issue warnings)
    If you move your return statement out of the finally block, it will work as you'd expect it.

  • A small clarification in Exception handling

    Please find the simpe program given below on Exception handling I have asked my query at the end of the program
    This program is about throwing a user defined exception when Command line arguments satisfieds one of the checked conditions. Thanks in advance:
    class myexcep extends Exception
    class exception
    public static void main(String arg[])
    try
    for(j = arg.length-1;j>=0;j--)
    checkfood(arg[j]);
    catch(myexcep e1)
    System.out.println("Exception " +e1);
    System.out.println("I dont like this ifood");
    e1.printStackTrace();
    public static void checkfood(String a) throws myexcep
    if (a.equals("Pizza") | a.equals("Brocolli") | a.equals("Pasta"))
    throw new myexcep();
    System.out.println("I like this food " +a);
    The program complies and runs succesfully. After compilation if I give
    c:> java exception cabbage Pizza sub
    3rd and 2nd arguments are evaluated sucessfully and a exception is thrown, when argument "Pizza" is encountered which is succesfully caught by catch block. SO program ends there without even looking at my first argument cabbage.
    Can anyone give me a suggestion as of how to evaluate String "cabbage".

    Swtich the for and the try ... like this:
        for(int j = arg.length-1;j>=0;j--) {
          try {
            checkfood(arg[j]);
          } catch(myexcep e1) {
            System.out.println("Exception " +e1);
            System.out.println("I dont like this ifood");
            e1.printStackTrace();
        }

  • Regarding static block

    Hi,
    I need to get two properties from the properties file and i will use these properties across the application,How can i write the util class which get the two properties and i can use acrross the application.
    Can i use the staic block in the util class ?
    Pls suggest me.
    Thanks
    crr

    I would use a util class to lazily load the properties file. You will need to handle certain IO exceptions when loading props, which is too much for a static block to handle properly. For example,
    public synchronized Properties getProps() {
        if(this.props == null) }
            loadProps();
        return this.props;
    }-cheng

Maybe you are looking for

  • Can I submit a jsp link to provide the XML feed from a dabase?

    Will a .jsp file that querries our database to provide formatted & tagged iTunes XML be allowed as a valid podcast link through iTunes? We are trying to provide our clients with multiple-title XMLs. This would be a great way for us to manage/schedule

  • Adding custom fields to BAPI_MATERIAL_SAVEDATA

    With the DFPS module, SAP has added the NSNID field to the MARA table. However, BAPI_MATERIAL_SAVEDATA makes use of structure BAPI_MARA, which does not have the same field included. When consulting SAP about this difference, we get the answer that we

  • How to display unicode character in jsp pages?

    i have to display user need language using unicode character according to user selected in radio button arabic or german in jsp pages. can you explain how i have to code?

  • How to identify VI's without callers?

    I have a .LLB containing a large number of VI's. How can I find the VI's which have no callers (main or obsolete VI's). I run LabVIEW 6.0. Thanks!

  • Organizer not working properly, please advise.

    The organizer imported all the thumbnails of my photos from my photo file but when i go to open that photo up it cant connect or find it. it does a "search" but its not found. i know my photos are there because i can open them directly from the photo