Async tests and Assert throws exceptions

Hi,
In a regular non-async test, something like Assert.assertEquals( "apples", "oranges" ); gives a nice report that the strings didn't match.  The test fails and the suite continues and all is good.  If the test is asynchronous, though, you get an uncaught exception, and a timeout on the test rather than a nice report.  Worse, it will cause a command-line based test to freeze with a stack trace showing (if you have a debug version of Flash, of course), until you hit the dismiss button.
Here's an example.  Without the Assert.assertEquals line, the test passes after two seconds as expected.  With the Assert.assertEquals in place, you get the behaviour I described.  So the question is, how do I use asserts in an asynchronous test?  I want the behaviour that you get with synchronous tests, i.e. a nice report and no pop-up dialog showing the stack.
        const TEST_COMPLETE:String = "testComplete";
        [Test(async)]
        public function myAsyncTest():void   
            Async.proceedOnEvent( this, this, TEST_COMPLETE, 5000 );
            var t:Timer = new Timer(2000, 1);
            t.addEventListener(TimerEvent.TIMER, timeout);
            t.start();
        private function timeout(e:Event):void
            Assert.assertEquals( "apples", "oranges" );
            dispatchEvent( new Event(TEST_COMPLETE) );
Any help?
Thanks!
DB

The code you have below doesn't do what you think it does.
When you setup an async test in FlexUnit, it needs to know what code is related to a given test. When you use items like the asyncHandler() methods, it basically calls that code in a way that watches for assertions and can manage to track them when they occur.
In your code, you are setting up a timer and that timer is calling another method which does an assertion. The timer calls that code directly from the top of the call stack... in other words, completely outside of FlexUnit. FlexUnit doesn't know your method is being called and cannot wrap the call in order to catch any information thrown from your assertion.
Can you describe what you want to do and I can advise you on the right syntax? It isn't that assertions work differently in async tests, it is that FlexUnit has no idea that the timeout() method is being called, Flash Player is calling it directly, and hence there is no way for it to watch the assertion.
I am guessing you want something more alogn the lines of this, but I am not sure:
Test(async)] 
public function myAsyncTest():void{
var t:Timer = new Timer(2000, 1); 
var handler:Function = Async.asyncHandler( this, timeout );t.addEventListener(TimerEvent.TIMER, handler );
t.start();
private function timeout(e:Event, passThroughData:Object ):void
Assert.assertEquals(
"apples", "oranges" );}

Similar Messages

  • HT3204 I have made sure my computer is updated, ran the connectivity tests and all passed except for cd player but I still cannot connect to iTunes store.

    I am not able to connect to iTunes store. I have tried all their suggstions o the Apple site. Ran all the connectivity tests and on the cd player came up as an error.

    Have you verified that the account information you have stored in iTunes on your computer, EXACTLY mirrors the information you have on file on your iPad?  For example, if you say you live on 1234 Road in iTunes, but on your iPad you say you live on 1234 Rd., you'll have an issue.  Make sure the information on both sides is the same.

  • Referenced native libraries getting pre-compiled and then throwing exception

    Hi I have an issue in the universal app. I am referencing Nokia.Graphics.Imaging.dll and WindowsPreview.Media.Ocr.dll in the universal app project. Everything compiles and runs on every device I tested it with. The problem is that after some time NGen kicks
    in and pre-compiles my DLLs, including the native ones. These DLLs then get corrupt and next time I run the app I get BadImageFormatException due to an attempt to load the <nativelibrary>.ni.dll. Is this a bug of NGen? When I delete these <nativelibrary>.ni.dll
    files the app runs again.

    Hi, unfortunately, I was not able to simulate this behavior in another project so far. Here
    http://uloz.to/xRShw487/precompiled-zip are NGENed files from our application (_not_working folder) and from a filter-manager sample (_working from different_app). As you can see for some reason Lumia.Imaging.ni.dll
    in our app has only 796kB, while from the other app it has 1235kB.
    The NGEN log file looks ok to me:
    03/23/2015 15:18:24.272 [11796]: 1>    Compiling assembly C:\Program Files\WindowsApps\app\Lumia.Imaging.Managed.DLL (CLR v4.0.30319) ...
    03/23/2015 15:18:24.350 [11796]: ngen returning 0x00000000
    03/23/2015 15:18:25.334 [24168]: 1>    Compiling assembly C:\Program Files\WindowsApps\app\WindowsPreview.Media.Ocr.winmd (CLR v4.0.30319) ...
    03/23/2015 15:18:25.365 [24168]: ngen returning 0x00000000
    03/23/2015 15:18:25.444 [8036]: 1>    Compiling assembly C:\Program Files\WindowsApps\app\Lumia.Imaging.winmd (CLR v4.0.30319) ...
    03/23/2015 15:18:25.725 [8036]: ngen returning 0x00000000
    Once I delete Lumia.Imaging.ni.dll and WindowsPreview.Media.Ocr.ni.dll, the app starts working again. Lumia.Imaging.Managed.DLL seems to be OK and does not cause any troubles, maybe because it is managed, while both of the problematic DLLs are native already.
    Hi LVolf,
    >>I am referencing Nokia.Graphics.Imaging.dll and WindowsPreview.Media.Ocr.dll in the universal app project
    How did you add these references in your project? Basically, the NuGet package is the easiest way, for example:
    See the
    NuGet documentation for all the ways you can download and install the NuGet package in your project. To install the package from within Microsoft Visual Studio, do the following:
    1.In Visual Studio, select PROJECT | Manage NuGet Packages.
    2.In the Online section, select nuget.org. Search for 
    Microsoft.Windows.Ocr.
    3.Click Install.
    4.Select BUILD | Configuration Manager to change the build configuration of your project from
    AnyCPU to x86, x64, or  ARM.
    5.If Intellisense does not work after you have installed the NuGet package, unload and reload the Visual Studio project. In Solution Explorer, right-click the project and select
    Unload Project. Then right-click the project again and select 
    Reload Project.
    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.

  • Core dump on throwing exception

    Hi,
    I am using an exception class derived from C++ standard exception class (MyException). In this, I am having a member variable of type std::string. I am using this in a DLL that is being used by Java application using JNI.
    In my C++ code, I am catching exception following way:
    catch(XException& exp)
    catch(MyException& exp)
    catch(exception& exp)
    If I am using std::string as member in MyException class, it results in a coredump whatever exception is thrown (MyException or any other unknown exception supposed to be caught in the standard exception class.). Note that this happens in release build of my dll and never repeatable in debug build.
    This problem occurs only in Solaris (tested both in Solaris 7 and Solaris 8). It does not occur in Windows.
    Now, if I use char array instead of std::string the problem does not occur!!!! Exceptions are caught properly.
    If anyone can throw more light on why usage of std::string causes issues in exception handling in Solaris using CC 5.0 compiler, it shall be of help. I feel problem might be due to not updating the patches related to CC 5.0 exception handling. Also, is it a good practise to use std::string in exception handling classes?

    C++ 5.0 is very old and is no longer supported. Patches are still available for it, however. You should get the latest patches from
    http://access1.sun.com/sundev
    and see if that solves your problem. If not, you should upgrade to a supported compiler release.
    The standard string class can perfrom dynamic memory allocation and can throw exceptions. It's not ideal for use in exception handling for those reasons. But for ordinary situations when you are not out of memory it' s probably OK.

  • Question about throws exception in interface and realized class

    Hi,all
    If I define a method In the interface like that-
    public void Execute() throws NumberFormatException; In the realized class, I can define this method like that-
    public void Execute() throws RuntimeException{
            System.out.println("test");       
    }This is a right realization. But if I manage it to throws Exception or to throws Throwable in the class it leads a error. Why add this restrict only to Exception? What is the purpose of this way?
    Greetings and thanks,
    Jason

    When you say "throws NumberFormatException" you are really saying:
    When using classes implementing this interface, you have to be prepared to deal with them throwing a NumberFormatException. Other exceptions won't happen.
    When you come to implement it, it might not be possible for it to throw a NumberFormatException, so there's no reason why you should have to lie about that. Code handling it directly will be fine (it doesn't throw a NFE) and code handling it via the interface will be fine (it will handle NFEs, they just don't happen).
    If your concrete implementation throws other sorts of exception, such as Exception or IOException, and so on, it's incompatible with code that's manipulating the interface. The interface says "NFEs might get thrown, nothing else will." while your implementation says "IOExceptions might get thrown".
    So that explains why you can't use arbitrary exceptions. The special case is RuntimeException. RuntimeExceptions don't have to be caught, and it's expected that they can happen at any time - so there's no point trying to catch and handle them as a general case.
    The classic example of a RuntimeException is a NullPointerException. You don't need to declare your method as throwing a NullPointerException even though it might get thrown. And you don't have to add NullPointerException to the throws part of the interface definition, because you already know that the concrete implementation could throw a NPE at any time.
    Hope that helps (a little).
    I'd recommend reading the API documentation on RuntimeException and Exception to get a clearer insight into this.
    Dave.

  • 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

  • Throws Exception in main and return code for JVM

    Hello,
    Could someone tell me what the following statement :
    public class Foo {
    public static void main(java.lang.String[] args) throws Exception {
    // Some source code
    is supposed to do with the return code of the VM when the Exception is thrown.
    I mean what num�ric value is supposed to return the following instruction :
    java -classpath ... com.app.Foo
    Because my Java program is run in a script shell which is supposed to get a return code which as to be interpreted.
    Off course I am not allowed to do the test myself because this script shell is executed on a production server ...

    I don't know what the return code will be, but you could do this:
    public static void main(String[] args)
      try
        // ...Run the program here...
      catch (Exception e)
        // Print the stack trace
        e.printStackTrace();
        // Exit with an error code
        System.exit(10);
    }Jesper

  • [svn] 4494: Added tests to hit channels and services configuration exceptions

    Revision: 4494
    Author: [email protected]
    Date: 2009-01-12 16:12:09 -0800 (Mon, 12 Jan 2009)
    Log Message:
    Added tests to hit channels and services configuration exceptions
    checkintests: passed
    Added Paths:
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/channels/
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/channels/DuplicateIdTest/
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/channels/DuplicateIdTest/error.t xt
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/channels/DuplicateIdTest/service s-config.xml
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/channels/InvalidIdTest/
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/channels/InvalidIdTest/error.txt
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/channels/InvalidIdTest/services- config.xml
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/BadDefaultChannelTest/
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/BadDefaultChannelTest/e rror.txt
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/BadDefaultChannelTest/s ervices-config.xml
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/DuplicateDefTest/
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/DuplicateDefTest/error. txt
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/DuplicateDefTest/servic es-config.xml
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/DuplicateDefaultAdapter Test/
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/DuplicateDefaultAdapter Test/error.txt
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/DuplicateDefaultAdapter Test/services-config.xml
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/IncorrectRootElementTes t/
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/IncorrectRootElementTes t/error.txt
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/IncorrectRootElementTes t/messaging-config.xml
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/IncorrectRootElementTes t/services-config.xml
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/InvalidAdapterIdTest/
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/InvalidAdapterIdTest/er ror.txt
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/InvalidAdapterIdTest/se rvices-config.xml
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/InvalidIdTest/
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/InvalidIdTest/error.txt
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/InvalidIdTest/services- config.xml
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/NoClassAttrTest/
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/NoClassAttrTest/error.t xt
    blazeds/trunk/qa/apps/qa-regress/testsuites/config/tests/services/NoClassAttrTest/service s-config.xml

    my connectivity is okay, I'm getting errors from domain controller itself, I checked and the network is okay, but  for the record here is my ipconfig /all
    Windows IP Configuration
       Host Name . . . . . . . . . . . . : server
       Primary Dns Suffix  . . . . . . . : ***.tk
       Node Type . . . . . . . . . . . . : Hybrid
       IP Routing Enabled. . . . . . . . : No
       WINS Proxy Enabled. . . . . . . . : No
       DNS Suffix Search List. . . . . . : ***.tk
    Ethernet adapter Ethernet:
       Connection-specific DNS Suffix  . :
       Description . . . . . . . . . . . : Intel(R) 82574L Gigabit Network Connectio
    n
       Physical Address. . . . . . . . . : 00-0C-29-32-7E-79
       DHCP Enabled. . . . . . . . . . . : No
       Autoconfiguration Enabled . . . . : Yes
       IPv4 Address. . . . . . . . . . . : 213.233.***.***(Preferred)
       Subnet Mask . . . . . . . . . . . : 255.255.255.0
       Default Gateway . . . . . . . . . : 213.233.***.1
       DNS Servers . . . . . . . . . . . : 127.0.0.1
       NetBIOS over Tcpip. . . . . . . . : Enabled

  • Besides throwing exceptions and the "return;" statement

    Besides throwing exceptions and the "*return*" statement, what else clauses could complete a code block abruptly?
    Originally I thought System.exit() should be one of that kind, and I was totally puzzled by the fact that finally clause dose not work with System.exit(). But after a few thoughts, it becomes clear to me that System.exit() dose not even complete a code block, let alone completing a code block abruptly. So is there other logic that could make a code block complete abruptly?
    My question originates from paragraphs in <Thinking in JAVA>, which claim that, I quote,
    "Unfortuantely, there's a flaw in Java's exception implementation. Although exceptions are an indication of a crisis in your program and should never be ignored, it's possible for an exception to simply be lost. This happens with a particular configuration using a finally clause"..."This is a rather serious pitfall, since it means that an exception can be completely lost, and in a far more subtle and difficult -to-detect fashion..."..."Perhaps a future version of Java will repair this problem"...
    After check with JLS, it seams that it is legitimate to ignore the reason for the abrupt completion of the try block, if the corresponding finally block completes abruptly. I think whether this is a "pitfall, flaw" or not depends on how deeply we language users understand the purpose of the finally clause and it is better for me to know all the possible reasons for a code block to complete abruptly.
    So, besides throwing exceptions and the "*return*" statement, what else clauses could complete a code block abruptly?

    warnerja wrote:
    Case 1: Normal flow (no exception is about to be bubbled to the caller before getting to the finally block) - I'd say we want an exception back due to the failure to close the stream.
    Case 2: The finally block was entered through an exception about to be bubbled to the caller - the caller can only get one or the other exception back, either the original exception or the one indicating the failure to close the stream. The finally block has no access to the pending exception however and is unaware of whether there is an exception pending or not. All it knows is an exception occurred during the execution of the finally block, and should throw that or wrap it in another exception - same handling as in Case 1.
    try {
      write();
      flush();
    finally {
      try {
        close();
      catch (...) {
        log();
    }The flush() at the end of try seems kind of redundant, since close() calls flush() anyway. The benefit is that the try statement completion matches the try block ("real work") completion.
    If we get to the end of the try block with no exception, then write() and flush() have succeeded and the data is where it needs to be. All that's left is to release the I/O resource, which will always be done in finally.
    If there's an exception in the try block, it is propagated out, so we know of any failure that occurred doing the "real work." The I/O resource is still released in finally.
    Regardless of how the try block completed, releasing the resource does not affect how the try statement completes, and hence does not supersede how our "real work" completes, which is all we care about. We still log any close() errors for later investigation. What matters to our program is whether all the data was written, and the completion of write() and flush() tells us that.

  • Difference in throwing and catching an exception?

    What is the difference between throwing an exception and catching an exception?

    Catching an exception is where the code you right says "Hey I am going to handle any exceptions coming this way"
    Throwing is where the method in which an exception is thrown says "I am not taking responsibility for any exceptions thrown"

  • Using assert or exception?

    I have been struggling with the methodology of using assertions for some time
    now and would like to have an objective viewpoint. It primarily has to
    do with the use of assertions for pre-conditions.
    Let's say we have some class, for demonstration purpose only, as this one:
    public class MyClass {
        private final String str;
        public MyClass(String str)
            this.str = str;
        private int getLength(String x, String y)
            return x.length() + y.length();
        public int getTotalLength(String x)
            return  getLength(str, x);
    }Let's say I want to make sure that the classes methods and constructor is not
    called with any null parameter. Of course I will get a NullPointerException
    eventually automatically anyway, but let's say I want to know as soon
    as possible to something is wrong. Or maybe I am dealing with a complicated
    class in which it is not so clear yet.
    Anyway the Sun Java documentation says the following:
    http://java.sun.com/j2se/1.4.2/docs/guide/lang/assert.html#preconditions
    "Do not use assertions to check the parameters of a public method."
    Instead it should throw some particular exception. In this case a
    NullPointerException in the MyClass constructor if the str parameter is
    null. Conventation say that assertion can be used for private methods
    however, such as the getLength method.
    I always try to keep my classes relatively small. So often I feel no desire
    to include assertions in private methods to check parameters if I can
    already see that the parameters are checked in the public methods.
    So in this case why add assertions in getLength if I can already clearly
    see that the parameters have been checked in the MyClass constructor and
    the getTotalLength method?
    Maybe I am wrong, but I am afraid that using such rigurous parameter testing
    in every public method might influence performance too much, because in
    contrary of assertions these normal checks are done always. I cannot
    remove these normal checks, because that would mean it could trigger
    an assertion in one of the private methods, and I could as well move
    the assertions from the private to the public methods.
    What I don't feel comfortable about is this big distinction between
    assertions and run-time exceptions. Why not use assertions in
    public methods for parameter testing? They are just exceptions
    too anyway. And they have the benefit of not impacting performance
    for production environments.
    There is an article about challenging the Sun Assert convention here.
    http://www.javaworld.com/javaworld/jw-12-2001/jw-1214-assert-p2.html
    I would like you to read it and give your objective opinion. Weighing
    the positive and negative implications of it and tell me what you
    think and why.

    I don't have the time to read that article. IMO
    assertions are to be used to validate the state of
    your instance and its internal works.So you do not think that assertions should be used for any pre-conditions of parameters?
    They are not
    exceptions, by the way. Failure will result in an
    AssertionError.Yes, I should have said errors or throwables.
    It's quite overkill IMO to use those for the
    validation of parameters provided by someone else.Why? Isn't it overkill to impact the performance by
    using run-time exceptions instead of assertions?
    If
    your API declares the legit value range of an
    argument, a NullPointerException for null and an
    IllegalArgumentException for values outside bounds,
    that gives me more flexibility to react and handle
    error states (it could be user input - null would
    mean there's a bug, out of bounds would mean I have
    to ask the user again) than merely firing of a "big"
    assertion error.But the whole idea of pre-conditions is that the method never must be called with invalid values. Your example might make sense for some class close to the front-end, but most classes are deep inside everything and have no idea what to do with a NullPointerException or IllegalArgumentException at that point. I would let a facade near the front-end deal with invalid user input and explicitly prevent the invalid input progress deeper inside my code.
    The article I linked goed deeper in about why it is a good idea to give a "big" assertion error at that point.
    There's probably no hard or objective rule when you
    should use what anyway, otherwise, there wouldn't be
    different opinions in this matter. If you're looking
    for one, you'll most likely not find it.I have certain ideas about assertions and I would like to know if these ideas are reasonable. Especially because they go against the Sun convention and I usually am a follower of standards.

  • Throwing Exception having multiple arguments in constructor

    hi,
    I am trying to implement exception handling for a JAVA + C++ module.
    In which C++ exception is caught by a Java module.
    The c++ code is as follows,
    try
    ///////////===========
    } catch (Exception1 &e) {
    jclass clazz = jenv->FindClass("test/Exception1Java");
    if(clazz)
    jenv->ThrowNew(clazz,e.getErrMsg().c_str());
    return 0;
    } catch (Exception2 &e) {
    jclass clazz = jenv->FindClass("test/Exception2");
    if(clazz)
    jenv->ThrowNew(clazz,e.getErrMsg().c_str());
    return 0;
    This works perfectly fine.
    But I want to pass one more argument as int while throwing the java exception.
    jenv->ThrowNew(clazz,e.getErrId(),e.getErrMsg().c_str());
    As the jenv->ThrowNew function only take two arguments I am unable to send the error id( int ) to the message.
    Is there any alternate to this function or some other approach to throw the java exceptions.

    hi,
    I am trying to implement exception handling for a
    JAVA + C++ module.
    In which C++ exception is caught by a Java module.
    The c++ code is as follows,<snip>
    >
    But I want to pass one more argument as int while
    throwing the java exception.
    env->ThrowNew(clazz,e.getErrId(),e.getErrMsg().c_str());>
    As the jenv->ThrowNew function only take two
    arguments I am unable to send the error id( int ) to
    the message.
    Is there any alternate to this function or some other
    approach to throw the java exceptions.Build the exception using the normal FindClass, GetMethodID approach,. and then throw it.
    #include "NativeExceptionTest.h"
    JNIEXPORT void JNICALL Java_NativeExceptionTest_test
    (JNIEnv *env, jobject obj, jint data) {
         if (data == 42) {
              jclass excClass = env->FindClass("MyException");
              if (!excClass) {
                   return;
              jmethodID ctorID = env->GetMethodID(excClass, "<init>", "(ILjava/lang/String;)V");
              if (!ctorID) {
                   return;
              jstring excMessage = env->NewStringUTF("ILLEGAL VALUE");
              jobject excObject = env->NewObject(excClass, ctorID,-1,excMessage);
              if (!excObject) {
                   return;
              env->Throw((jthrowable)excObject);
         return;
    }============================================
    public class NativeExceptionTest {
         static {
              System.loadLibrary("nativeException");
         NativeExceptionTest() {
               try {
                    test(42);
               } catch (MyException e) {
                   System.out.println("Exception: " + e.getCode() + "(" + e.getMessage() +")");
         private native void test(int i) throws MyException;
         public static void main(String[] args) {
              new NativeExceptionTest();
    class MyException extends Exception {
         private int code;
         MyException(int code, String message) {
              super(message);
              this.code = code;
         int getCode() {
              return this.code;
    }

  • Using sql bulk copy throwing exception -The given value of type String from the data source cannot be converted to type int of the specified target column

    Hi All,
    I am reading notepads files and inserting data in sql tables from the notepad-
    while performing sql bulk copy on this line it throws exception - "bulkcopy.WriteToServer(dt); -"data type related(mentioned in subject )".
    Please go through my  logic and tell me what to change to avoid this error -
    public void Main()
    Dts.TaskResult = (int)ScriptResults.Success;
    string[] filePaths = Directory.GetFiles(@"C:\Users\jainruc\Desktop\Sudhanshu\master_db\Archive\test\content_insert\");
    for (int k = 0; k < filePaths.Length; k++)
    string[] lines = System.IO.File.ReadAllLines(filePaths[k]);
    //table name needs to extract after = sign
    string[] pathArr = filePaths[0].Split('\\');
    string tablename = pathArr[9].Split('.')[0];
    DataTable dt = new DataTable(tablename);
    |
    string[] arrColumns = lines[1].Split(new char[] { '|' });
    foreach (string col in arrColumns)
    dt.Columns.Add(col);
    for (int i = 2; i < lines.Length; i++)
    string[] columnsvals = lines[i].Split(new char[] { '|' });
    DataRow dr = dt.NewRow();
    for (int j = 0; j < columnsvals.Length; j++)
    //Console.Write(columnsvals[j]);
    if (string.IsNullOrEmpty(columnsvals[j]))
    dr[j] = DBNull.Value;
    else
    dr[j] = columnsvals[j];
    dt.Rows.Add(dr);
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = "Data Source=UI3DATS009X;" + "Initial Catalog=BHI_CSP_DB;" + "User Id=sa;" + "Password=3pp$erv1ce$4";
    conn.Open();
    SqlBulkCopy bulkcopy = new SqlBulkCopy(conn);
    bulkcopy.DestinationTableName = dt.TableName;
    bulkcopy.WriteToServer(dt);
    conn.Close();
    Issue 1:-
    I am reading notepad: getting all column and values in my data table now while inserting for date and time or integer field i need to do explicit conversion how to write for specific column before bulkcopy.WriteToServer(dt);
    Issue 2:- Notepad does not contains all columns nor in specific sequence in that case i can add few column ehich i am doing now but the issue is now data table will add my columns + notepad columns and while inserting how to assign in perticular colums?
    sudhanshu sharma Do good and cast it into river :)

    Hi,
    I think you'll have to do an explicit column mapping if they are not in exact sequence in both source and destination.
    Have a look at this link:
    https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlbulkcopycolumnmapping(v=vs.110).aspx
    Good Luck!
    Kaur.
    Please mark as answer if this resolves your issue.

  • EndTransaction(wf_Commit) throws exception on SQL2005 (on SQL2000 it works)

    Hello @all!
    Our AddOn is creating an invoice (documents-business-object) and doing some querys (INSERTs, SELECTs and UPDATEs). This process is completely done within the StartTransaction/EndTransaction Methods.
    After upgrade the customer DB to SBO SP01/PL27 and MSSQL 2005 the EndTransaction(wf_Commit) throws an exception. Rolling back the transaction for testing works without exception.
    All querys in the process are working without exception.
    We have upgraded our customer in the following way:
    1. On SBO SP00/PL13 we have installed SQL2005. This worked fine for some weeks.
    2. Then we have installed SBO SP01/PL27 and from then the problem from above occurs.
    On our development server with MSSQL2000 and also SP01/PL27 the process works fine with the same AddOn.
    Has anybody made similar experiences or a solution?
    Best regards,
    Roland

    Hi William,
    the DI-API was also updated manually.
    But I FORGOT the error-message. It is
    "There is no active transaction in progress"
    which occurs directly after checking for an active transaction:
    If SboDI.InTransaction then ' <= This is TRUE.....
       SboDI.EndTransaction(wf_Commit) '<= ...and this throws the"...no active transaction.."-error
    End If
    @Felipe:
    I have opened a ticket (it's answered). I have to create a sample code which is difficult because of many UserFields and -Tables (and the DB is very large)
    And the news:
    Today I have heard from our customer that the Fixed Assets AddOn has ended with the same error:
    "There is no active transaction in progress"

  • Advanced Datagrid GroupingCollection of flat data (XMLLISTCollection) while sorting throws exception

    HI,
         Iam using AdvancedDatagrid inorder to group the flat data populated from the backend through BlazeDS. Result data will be in xml format and i have converted it to xmllistcollection and assigned to the grouping collection source. Flat data is grouped by one of the attribute called 'Name' and refreshed after data has been populated.
    Data structre used as input is: WIth this structure, iam grouping by the field 'Name'.
      <Report> <att_report>
      <id>FDR1</id>
      <Name>Feeder 1</Name>
      <frequency>Monthly</frequency>
      <Field>Finance 1</Field>
      <Aug_10>100</Aug_10>
      <Jul_10>200</Jul_10>
    </att_report>
    <att_report>
      <id>FDR1</id>
      <Name>Feeder 1</Name>
      <frequency>Yearly</frequency>
      <Field>Finance 2</Field>
      <Jul_10>200</Jul_10>
    </att_report>
    <att_report>
      <id>FDR2</id>
      <Name>Feeder 2</Name>
      <frequency>Quarterly</frequency>
      <Field>Finance 3</Field>
      <Jul_10>2000</Jul_10>
    </att_report>
    <att_report>
      <id>FDR2</id>
      <Name>Feeder 2</Name>
      <frequency>MOnthly</frequency>
      <Field>Finance 2</Field>
      <Jul_10>2000</Jul_10>
    </att_report>
    <att_report>
      <id>FDR4</id>
      <Name>Feeder 4</Name>
      <frequency>yearly</frequency>
      <Field>Finance 5</Field>
      <Jul_10>2000</Jul_10>
    </att_report>
    </Report>
    Grouping is done as expected. We have additional functionalities like soring / seraching of the result set. Either one is working fine. Other functionality throws excpetion mentioned below.
    When any of the advanced datagrid grid column header is clicked for sorting, it throws exception. I have pasted the exception below for reference.
    TypeError: Error #1009: Cannot access a property or method of a null object reference.
    at mx.collections::HierarchicalCollectionView/internalRefresh()[C:\work\flex\dmv_automation\ projects\datavisualisation\src\mx\collections\HierarchicalCollectionView.as:709]
    at mx.collections::HierarchicalCollectionView/refresh()[C:\work\flex\dmv_automation\projects \datavisualisation\src\mx\collections\HierarchicalCollectionView.as:686]
    at mx.controls::AdvancedDataGridBaseEx/sortHandler()[C:\work\flex\dmv_automation\projects\da tavisualisation\src\mx\controls\AdvancedDataGridBaseEx.as:6869]
    at mx.controls::AdvancedDataGrid/sortHandler()[C:\work\flex\dmv_automation\projects\datavisu alisation\src\mx\controls\AdvancedDataGrid.as:6899]
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at mx.core::UIComponent/dispatchEvent()
    at mx.controls::AdvancedDataGrid/headerReleaseHandler()[C:\work\flex\dmv_automation\projects \datavisualisation\src\mx\controls\AdvancedDataGrid.as:7120]
    at flash.events::EventDispatcher/dispatchEventFunction()
    at flash.events::EventDispatcher/dispatchEvent()
    at mx.core::UIComponent/dispatchEvent()
    at mx.controls::AdvancedDataGridBaseEx/mouseUpHandler()[C:\work\flex\dmv_automation\projects \datavisualisation\src\mx\controls\AdvancedDataGridBaseEx.as:5738]
    at mx.controls::AdvancedDataGrid/mouseUpHandler()[C:\work\flex\dmv_automation\projects\datav isualisation\src\mx\controls\AdvancedDataGrid.as:8457]
    I tried with couple of options but still not able to get rid of the excpetion. I browsed through couple of links also, still not able to find an solution. Can i know whether it is a bug or it can be fixed.
    Any help / suggestions on this will be great.
    Thanks in Advance,
    Srinivasan

    Read the error messages and pay attention to the line number of the error:
    1)1 import java.io.*;
    2
    3 public class Test
    4 {
    5   public static void openFile()
    6   {
    7     FileOutputStream f = new FileOutputStream("data.txt");
    8   }
    9
    10   public static void main (String[] args)
    11   {
    12     openFile();
    13   }
    14 }
    $ javac -cp "" Test.java
    Test.java:7: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
        FileOutputStream f = new FileOutputStream("data.txt");
                             ^
    1 error2)1 import java.io.*;
    2
    3 public class Test
    4 {
    5   public static void openFile() throws FileNotFoundException
    6   {
    7     FileOutputStream f = new FileOutputStream("data.txt");
    8   }
    9
    10   public static void main (String[] args)
    11   {
    12     openFile();
    13   }
    14 }
    $ javac -cp "" Test.java
    Test.java:12: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
        openFile();
                ^
    1 error3)
    1 import java.io.*;
    2
    3 public class Test
    4 {
    5   public static void openFile() throws FileNotFoundException
    6   {
    7     FileOutputStream f = new FileOutputStream("data.txt");
    8   }
    9
    10   public static void main (String[] args)
    11   {
    12     try
    13     {
    14       openFile();
    15     }
    16     catch(FileNotFoundException e)
    17     {
    18       System.out.println("Error file doesn't exist.");
    19     }
    20   }
    21 }
    $ javac -cp "" Test.java
    $
    1 import java.io.*;
    2
    3 public class Test
    4 {
    5   public static void openFile() throws FileNotFoundException
    6   {
    7     FileOutputStream f = new FileOutputStream("data.txt");
    8   }
    9
    10   public static void main (String[] args) throws FileNotFoundException
    11   {
    12     openFile();
    13   }
    14 }
    $ javac -cp "" Test.java
    $

Maybe you are looking for

  • Cant hear on first call but works on second call!

    My wife and I both got Xperia Z1's at the start of November.  Recently my wife has been having a problem with her phone. Nearly every time she calls me I cant hear her but she can hear me. If she hangs up and phones me back it works fine! Anyone got

  • Problem with infotype 16

    Hello. I expose my problem. We Need The InfoType 16 'for each person With The fieldname LFZFR. In This feld we include the days to pay the Illness. For ex. we pay 42 Days. You Will include 15 days. This is the field we need for reporting. That's beca

  • Good Receipt for PO With Network

    Dear gurus, I have a problem with Good Receipt PO with Network. How to make so just quantity with no value in inventory when i GR that PO?. But in same plant too we can GR PO without Network. so quantity and value enter in inventory. Thx.

  • Why is InDesign CS6 loading extremely slow????

    The company I work for has bought several licensed copies of the creative suite and ever since it was installed; the machine with the following specifications that I use: CPU: i7-3770 @ 3.4 (4 core, 8 threads, 8mb cache) O/S: Windows 7 Home Premium 6

  • Application source path

    Hi, i need to find CM12 application (deployment type) source paths. select ContentSourcePath from fn_ListApplicationCIsWithLatestTime(1033) returns empty values in my environment.  I tried Select name,pkgsourcepath from v_package and i does return ap