How to capture Java Exceptions in batch file

I have a batch file that calls java class. When the java class throws exception, how do I capture the exception as an error message in batch file.
This is the java program
import java.io.*;
public class Test{
       public static void main(String []args) {
     String wantThisToFail=null;
          try {
               if (wantThisToFail.equals("SomeString") ) {
                    System.out.println("Testing");     
          }catch (Exception e){
               System.out.println("Exception " + e);
This is the batch file
@echo off
echo Testing
REM execute the java class
java Test
set deployError=%ERRORLEVEL%
echo %deployError%
IF NOT %deployError% == 0 (
echo failed
)else (
echo succeeded
)Since the java class throws NullPointerException, i want the batch file to show "Failed" Message.
Please Help!!

Try capturing the return value of the command "java Test". If it succeeds, you should get a '0', otherwise you'll get something else. I admit it's been years since I had to do that, but it rings a bell. If it works, and you're on Java 5 or later, you can use the method Thread.setDefaultUncaughtExeptionHandler ( look at the docs ) and from there use System.exit(<your integer value return code here>) for more control over the return value

Similar Messages

  • How to creating concurrent call in batch file

    Hallo,
    I want to write a batch file under windows to call 6 instances concurrently to test whether the program is thread-safe. Below is the shell script for linux to create parallel call, it works. But if I use the same syntax, i.e. "&" to connect "java" call in batch file under windows, it only creates serial call, not concurrent call.
    How can I write a windows script or a batch file under windows to build parallel call.
    Best Regards
    saarxfk
    parallelCall.sh
    # set the classpath
    export CLASSPATH=
    for i in jars/*jar; do export CLASSPATH=$CLASSPATH:$i; done
    java WinsServiceClient morganti.pdf morganti.pdf it &
    java WinsServiceClient alesi.pdf alesi.pdf it &
    java WinsServiceClient morganti2.pdf morganti2.pdf it &
    java WinsServiceClient alesi2.pdf alesi2.pdf it &
    java WinsServiceClient morganti3.pdf morganti3.pdf it &
    java WinsServiceClient alesi3.pdf alesi3.pdf it
    ------------------------------------------------------------------------------------------------

    Hallo,
    I want to write a batch file under windows to call 6
    instances concurrently to test whether the program is
    thread-safe. Below is the shell script for linux to
    create parallel call, it works. But if I use the same
    syntax, i.e. "&" to connect "java" call in batch
    file under windows, it only creates serial call, not
    concurrent call.
    How can I write a windows script or a batch file
    under windows to build parallel call.
    You can't do that in windows from one shell. Open 6 shells and do it manually

  • How to pass arguments to a batch file from java code

    Hi
    I have a batch file (marcxml.bat) which has the following excerpt :
    @echo off
    if x==%1x goto howto
    java -cp C:\Downloads\Marcxml\marc4j.jar; C:\Downloads\Marcxml\marcxml.jar; %1 %2 %3
    goto end
    I'm calling this batch file from a java code with the following line of code:
    Process p = Runtime.getRuntime().exec("cmd /c start C:/Downloads/Marcxml/marcxml.bat");
    so ,that invokes the batch file.Till that point its ok.
    since the batch file accpets arguments(%1 %2 %3) how do i pass those arguments to the batch file from my code ...???
    %1 is a classname : for ex: gov.loc.marcxml.MARC21slim2MARC
    %2 is the name of the input file for ex : C:/Downloads/Marcxml/source.xml
    %3 is the name of the output file for ex: C:/Downloads/Marcxml/target.mrc
    could someone help me...
    if i include these parameters too along with the above line of code i.e
    Process p = Runtime.getRuntime().exec("cmd /c start C:/Downloads/Marcxml/marcxml.bat gov.loc.marcxml.MARC21slim2MARC C:\\Downloads\\Marcxml\\source.xml C:\\Downloads\\Marcxml\\target.mrc") ;
    I get the following error :
    Exception in thread main java.lang.Noclassdef foundError: c:Downloads\marcxml\source/xml
    could some one tell me if i'm doing the right way in passing the arguments to the batch file if not what is the right way??
    Message was edited by:
    justunme1

    1 - create a java class (Executer.java) for example:
    import java.lang.reflect.InvocationTargetException;
    import java.lang.reflect.Method;
    public class Executer {
         public static void main(String[] args) {
              try {
                   for (int i = 0; i < args.length; i++) {
                        System.out.println(args);
                   Class<?> c = Class.forName(args[0]);
                   Class[] argTypes = new Class[] { String[].class };
                   Method main = c.getDeclaredMethod("main", argTypes);
                   // String[] mainArgs = Arrays.copyOfRange(args, 1, args.length); //JDK 6
                   //jdk <6
                   String[] mainArgs = new String[args.length - 1];
                   for (int i = 0; i < mainArgs.length; i++) {
                        mainArgs[i] = args[i + 1];
                   main.invoke(null, (Object) mainArgs);
                   // production code should handle these exceptions more gracefully
              } catch (ClassNotFoundException x) {
                   x.printStackTrace();
              } catch (NoSuchMethodException x) {
                   x.printStackTrace();
              } catch (IllegalAccessException x) {
                   x.printStackTrace();
              } catch (InvocationTargetException x) {
                   x.printStackTrace();
              } catch (Exception e) {
                   e.printStackTrace();
    2 - create a .bat file:
    @echo off
    java -cp C:\Downloads\Marcxml\marc4j.jar; C:\Downloads\Marcxml\marcxml.jar; Executer %TARGET_CLASS% %IN_FILE% %OUT_FILE%3 - use set command to pass variable:
    Open MS-DOS, and type the following:
    set TARGET_CLASS=MyTargetClass
    set IN_FILE=in.txt
    set OUT_FILE=out.txt
    Then run your .bat file (in the same ms dos window)
    Hope that Helps

  • Please help how to run System commands and batch files thru java program

    Sir,
    I want execute OS commands like dir,cls..etc and batch files,.exe filesthru java program.
    I have tried it sofar thru Runtime.getRuntime().exec("execute.bat");
    but it is not working.anybody knows about how to run the system commands thru java please give me the code.
    thank you,
    regards,
    j.mouli

    I've seen other posts with this questions, and answers. Unfortunately I didn't pay much attention. But the basic idea is to exec command.com and pass the specifc batch or command as an argument.

  • How to include commandline options in Batch File

    Hi i have following code for batch file now i want to include one more optionas -savemndl
    command is
    loader.bat -savemndl (savedmndl file) (inputmndl file) (output Logfile)
    @echo off
    set JAVAOPTS= -Xms20m -Xmx500m %JAVAOPT%
    set FILE=
    set OPTIONS=
    :loop
      if "%1" == ""             goto break
      if "%1" == "-v"           goto setOptions
      if "%1" == "-print_mndl"  goto setOptions
      if "%1" == "-verbose"     goto setOptions
      if "%1" == "-seed"        goto setJavaOpt
      if "%1" == "-help"        goto help
      goto break
    :setOptions
      set OPTIONS=%OPTIONS% %1
      shift
      goto loop
    :setJavaOpt
      shift
      set JAVAOPTS=%JAVAOPTS% -Drandom.seed=%1
      shift
      goto loop
    :break
    if not exist "%1" goto notFound
    native2ascii %1 > %1.tmp
    set FILE=%1.tmp
    shift
    java %JAVAOPTS% -classpath classes;lib\simcore.jar;lib\loader.jar jp.go.nict.msf.loader.MNDLParser %OPTIONS%  %FILE% %1
    del %FILE%
    goto end
    :help
    echo usage: loader -help
    echo usage: loader [-v] [-seed value] [-print_mndl] filename.mndl [traceLogFile]
    java -classpath classes;lib\simcore.jar;lib\loader.jar jp.go.nict.msf.loader.MNDLParser -help
    goto end
    :notFound
    echo loader: Error "%1" is not found.
    echo usage: loader -help
    echo usage: loader [-v] [-seed value] [-print_mndl] filename.mndl [traceLogFile]
    :end

    And what is the actual quesion then? Because the batch file given above is itself a good example how to use parameters.
    Mike

  • How to capture errors records in flat file in BDC

    hi ,
        i would like to know how to capture error records while  uploading a flat file to screen through BDC .
    appreciatable solutions are rewarded.
    thanks,
    shan

    Hi shan,
    write this code, it will solve your problem.
    DATA : BDCTAB LIKE BDCDATA OCCURS 0 WITH HEADER LINE.
    DATA : I_MSG LIKE BDCMSGCOLL OCCURS 0 WITH HEADER LINE.
    DATA : BEGIN OF I_ERR OCCURS 0,
              MATNR(18),
              FLAG(1),
              MSG(100),
           END OF I_ERR.
    DATA :V_LINES TYPE I.
    LOOP AT ITAB.
    REFRESH BDCTAB.
    PERFORM SCREEN USING: 'SAPLMGMM' '0060'.
    PERFORM FIELD USING: 'RMMG1-MATNR'  ITAB-MATNR,
                          'RMMG1-MBRSH' ITAB-MBRSH ,
                          'RMMG1-MTART' ITAB-MTART,
                          'BDC_OKCODE' '/00'.
    PERFORM SCREEN USING: 'SAPLMGMM' '0070'.
    PERFORM FIELD USING: 'MSICHTAUSW-KZSEL(01)' 'X' ,
                         'MSICHTAUSW-KZSEL(02)' 'X' ,
                         'MSICHTAUSW-KZSEL(09)' 'X' ,
                         'BDC_OKCODE' '=ENTR'.
    PERFORM SCREEN USING: 'SAPLMGMM' '0080'.
    PERFORM FIELD USING: 'RMMG1-WERKS' ITAB-WERKS,
                         'BDC_OKCODE' '=ENTR'.
    PERFORM SCREEN USING: 'SAPLMGMM' '4004'.
    PERFORM FIELD USING:  'MAKT-MAKTX' ITAB-MAKTX,
                          'MARA-MEINS' 'EA' ,
                          'MARA-MATKL' '001',
                          'BDC_OKCODE' '/00'.
    PERFORM SCREEN USING: 'SAPLMGMM' '4004'.
    PERFORM FIELD USING:  'BDC_OKCODE' '/00'.
    PERFORM SCREEN USING: 'SAPLMGMM' '4000'.
    PERFORM FIELD USING:  'MAKT-MAKTX' ITAB-MAKTX,
                          'MARA-MEINS' 'EA',
                          'MARC-EKGRP' '001',
                          'MARA-MATKL' '001',
                          'BDC_OKCODE' '=BU'.
    CALL TRANSACTION 'MM01' USING BDCTAB
                            MODE 'A'
                            MESSAGES INTO I_MSG.
    FINDING LAST MESSAGE IN THE I_MSG TABLE*****
    DESCRIBE TABLE I_MSG LINES V_LINES.
    ACCORDING TO THE V_LINES NUMBER TABLE WILL BE READ****
    READ TABLE I_MSG INDEX V_LINES.
    CALL FUNCTION 'FORMAT_MESSAGE'
    EXPORTING
       ID              = I_MSG-MSGID
       LANG            = '-D'
       NO              = I_MSG-MSGNR
       V1              = I_MSG-MSGV1
       V2              = I_MSG-MSGV2
       V3              = I_MSG-MSGV3
       V4              = I_MSG-MSGV4
    IMPORTING
       MSG             = I_ERR-MSG
    EXCEPTIONS
       NOT_FOUND       = 1
       OTHERS          = 2
    IF sy-subrc <> 0.
    MESSAGE ID SY-MSGID TYPE SY-MSGTY NUMBER SY-MSGNO
             WITH SY-MSGV1 SY-MSGV2 SY-MSGV3 SY-MSGV4.
    ENDIF.
    IF I_MSG-MSGID EQ 'M3' AND I_MSG-MSGNR EQ '800'.
    I_ERR-FLAG = 'S'.
    ELSE.
    I_ERR-FLAG = 'E'.
    ENDIF.
    I_ERR-MATNR = ITAB-MATNR.
    APPEND I_ERR.
    CLEAR I_ERR.
    ENDLOOP.
    WRITE:/ 'SUCCESS RECORDS' COLOR COL_POSITIVE.
    SKIP.
    WRITE:/ 'MATERIAL' COLOR COL_HEADING, 20 'MESSAGE' COLOR COL_HEADING.
    LOOP AT I_ERR WHERE FLAG EQ 'S'.
    WRITE:/ I_ERR-MATNR, 20 I_ERR-MSG.
    ENDLOOP.
    SKIP 2.
    WRITE:/ 'ERROR RECORDS' COLOR COL_NEGATIVE.
    SKIP.
    WRITE:/ 'MATERIAL' COLOR COL_HEADING, 20 'MESSAGE' COLOR COL_HEADING.
    LOOP AT I_ERR WHERE FLAG EQ 'E'.
    WRITE:/ I_ERR-MATNR, 20 I_ERR-MSG.
    ENDLOOP.
    *&      Form  SCREEN
         SCREEN
    form SCREEN  using P_PROG P_SCREEN.
    BDCTAB-PROGRAM = P_PROG.
    BDCTAB-DYNPRO = P_SCREEN.
    BDCTAB-DYNBEGIN = 'X'.
    APPEND BDCTAB.
    CLEAR  BDCTAB.
    endform.                    " SCREEN
    *&      Form  FIELD
       FIELD
    form FIELD  using  FNAME FVAL .
    BDCTAB-FNAM = FNAME.
    BDCTAB-FVAL = FVAL.
    APPEND BDCTAB.
    CLEAR BDCTAB.
    endform.                    " FIELD
    Thanks,
    Murali

  • Query regarding running Java application from Batch file

    Hi,
    I have written an application in Java and I have packaged it as a JAR file.
    In my system I use a batch file called 'run.bat' to execute the program. The batch file is as follows:
    java -classpath "%CLASSPATH%;editor.jar" editor.JPad
    This works fine in my system. But when it is executed in other systems where JRE is not configured properly, I am not able to correctly start the Java application.
    Please can anybody tell me, how to detect the JRE from the Batch file and refer to it correctly, so that it will run in any system with JRE.
    Can we do this from a Batch file ?
    Hoping for a quick reply.
    Thanks,
    S.Sampath

    You can't really "detect" whether a JRE is available from a batch. All I can think of is to check for the typical Java variables (JVM_HOME, CLASSPATH etc) to exist. If they don't, especially JVM_HOME, a JRE is probably not installed.

  • Compile and run java programs using batch file

    i am using eclipse to run my java programs.How to compile and run those programs using a batch file?

    a) just write a batch file, and add it to the project. When you want to run it, go to a command window and invoke it. (There is probably also a way to invoke it from Eclipse)
    b) if the project is complicated, take a look at ant. Eclispe knows about ant files.

  • Closing Console window while running Java application from Batch file

    Hi all,
    I have made a small application using Java swings,now i have made a jar file of my application and calling this jar file through batch file,when user clicks on that batch file it runs "java -jar applicationname.jar" command,but problem is that when i run that file from batch file it opens Dos console window at baclk of the screen which looks weird for a desktop application,i dnt want that Dos console window visible at the backend while my application is running,i have searched regarding this on google but found nothing usefull,if anybody can please help regarding that it will be a great releif for me,i have been stuck on this problem from last two days.
    Thanks.
    Simer

    warnerja wrote:
    georgemc wrote:
    warnerja wrote:
    start java -jar applicationname.jar
    That'll pop up another consoleI'm under the impression that the console window he is seeing is the one which cmd.exe opens when it is executing the batch file. And that batch file won't return until the java process has completed because he didn't start it in the background to let the batch file continue and terminate.
    So I don't think just simply substituting java with javaw will do much good either. Still think he needs a "start" command in that batch file.
    So now he can try:
    start java -jar ...
    or
    start javaw -jar ...Fair point

  • How to capture Sony Hvr Z7 m2t Files FCPX 10.1.1

    Can any one help me there.
    I have a Sony Hvr Z7 - I can capture it with log and transfer with FCP7 or convert it with many programs out there. But
    I wanto to know how to capture straight from the Memory Recording Unit  connected by fire wire.
    Any Help there would much preciated
    Thanks

    First of all thanks for your answering. I know that.  But somewhere I came acros a way to do it
    but I have lost the link of it. I know, or think I know, there is a way. Kind a of archive or something like that.
    What I remember is that I had to import all the cf at once - and not been able to import file by file.
    I'll keep looking for it. If I find I'll post it here.
    Thanks any way!

  • How to write sql command in batch file

    hi,
    i m using oracle 9i on windows. i want to know how can i write sql command on batch file. i want to use a batch file to use sql command like shutdowm & startup command and any select command too.
    so plz tell how can i do it ?
    thxs

    superdba wrote:
    thxs u all , i got it at i wanted to do.
    thaks u all for yr precious time.
    thxsYou've 67 questions with 63 UNanswered. Please mark this question as "answered" and give points to the users whose answer you accept as "helpful" or "correct"
    Kamran Agayev A. (10g OCP)
    http://kamranagayev.wordpress.com
    [Step by Step install Oracle on Linux and Automate the installation using Shell Script |http://kamranagayev.wordpress.com/2009/05/01/step-by-step-installing-oracle-database-10g-release-2-on-linux-centos-and-automate-the-installation-using-linux-shell-script/]

  • How to check a checkbox in batch file

    Hello Guys,
    Heres an easy for you guys but nightmare for me question: I'm writing a batch file to login to sharepoint site. But I need to be able to check the "keep me signed" box also. How do I make my batch file to auto check that?
    I will attach my codes and site link for you guys to find out what the "checkbox" is called...
    Thank You in advance..
    The link is http://fwmc.sharepoint.com
    Here is my code: 
    set WshShell = WScript.CreateObject("WScript.Shell")
    call WshShell.Run("http://fwmc.sharepoint.com", 1, false) 
    WScript.Sleep 2000
    WshShell.SendKeys "[email protected]"
    WScript.Sleep 2000
    WshShell.SendKeys "{TAB}"
    WScript.Sleep 2000
    WshShell.SendKeys "userpassword"
    WshShell.SendKeys "{TAB}"
    WScript.Sleep 2000
    WshShell.SendKeys "{ENTER}"
    WScript.Quit()

    Heres an easy for you guys but nightmare for me question: I'm writing a batch file to login to sharepoint site. But I need to be able to check the "keep me signed" box also. How do I make my batch file to auto check that?
    This is a nightmare for you because the SendKeys method cannot be relied upon. Why? Because you can never be sure where the current focus is. While it is possible to place a tick mark by sending a space (instead of ENTER!), you will find that it will work some
    of the time and it won't some other times. Any unexpected pop-up will derail your script. If you need robust code then you must avoid SendKeys.

  • How to run Java App in Jar file

    I can run Java App jar-ed into 1 jar file with java -jar App.jar
    But sometimes I need to jar only the app and bind the other classes from different place. So I tried to use:
    java -classpath c:\utils.jar -jar App2.jar
    where classes in App2.jar link to utils.jar. I just can't make it work. Any idea/help.
    thanks
    -ho

    hi HasanOen
    u need to edit the manifest file in yr JAR file u can do this by using the following cammand or by making the batch file but make sure all the files are in same folder.
    first of all u need to make a text file like below
    /////////// first file name: "THIS.txt" /////////
    Manifest-Version: 1.0
    Created-By: java // whatever here
    Main-Class: PUT YOUR MAIN CLASS NAME HERE (like MAIN)
    //////////////////// BATCH FILE "RUN.bat" //////////////
    jar cmf This.txt App2.jar MANIFEST.mf com
    com is the folder where your all the class file are.
    now double click the run.bat file. this will edit yr manifest file.
    hope this should work for u
    Note : Make sure yr jar file, txt file, bat file, and yr classes folder is in the same folder(I mean at same level)
    regards
    Satinderjit

  • Running the Java Code from Batch File

    Hi All,
    I have run a code sucessfully in Eclipse and it uses Logging API from Java
    When i try running the same program from batch file it throws error
    java.io.IOException: Couldn't get lock for log\Properties_Log_16Sep2009_150229
    at java.util.logging.FileHandler.openFiles(Unknown Source)
    at java.util.logging.FileHandler.<init>(Unknown Source)
    at com.adidas.SPM.LogMessage.<init>(LogMessage.java:26)
    at com.adidas.SPM.MainApplication.initialize(MainApplication.java:51)
    at com.adidas.SPM.MainApplication.main(MainApplication.java:102)
    I am working on a windows systems the folder log has all the permission i have provided with all
    Not sure why the code runs like this
    The batch file is like below
    set CURR_DIR=%CD%
    cd %CURR_DIR%\bin
    %CURR_DIR%\jre6\bin\java -classpath .;%CURR_DIR%\lib\FirstProject.jar com.test.MainApplication
    echo %ERRORLEVEL% The Error Level
    echo SUCCESS
    GOTO END
    :END
    pause
    Rgds
    Aditya

    Vikash.SunJava wrote:
    According to me the problem is that there are many instances trying to access the same property file. Nothing wrong with that since they only are reading it.
    The best way to do is that create a schedular in Windows that runs at some predefined interval (say 1 minute).Huh?
    >
    What will happen is if your program runs for more than a minute even then the new process will not start until old process is autaomatically killed. Please do not check this option if you want the program to exit normally.
    If the Task is still running stop at this time
    O_o

  • Java.  Starting Batch files

    Is it possible to run batch files from a java program?

    Navigate yourself around pitfalls related to the Runtime.exec() method:
    http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html

Maybe you are looking for

  • Archiving TXT files in Sender File Adapter--Unformatted Way

    Hello, I am Archiving TXT files thru Sender file adapter, files are getting archived to specified directory.No issues in that., When i open the archived files, those are not in the correct format way that i placed before file pickup. Header & lines g

  • Firefox will not open and states that its already running. But is not?

    After several opening and closing of Firefox several time it will not open when I click on the desk top icon. A screen will come up that Firefox is already running and that I will have to close it before I can start Firefox. To correct this I have to

  • Web pages not accessible ( timeout)

    I am at a complete loss with a problem that I am having with a server that I want to use as a web server, and I am hoping that someone may have some ideas on what is going on. I have 5 Xserves doing various things however the one that I need to use a

  • MiniDv to VGA Windows 7

    Can not get Windows 7 to display on my TV with VGA adapter works great in Mac OSx I'm using boot camp have upgraded to 3.2 also tried upgrading to latest Nivida drivers still get a message that say not valid video signal change setting to 1280 x 768

  • Problem with forward

    In my start page - page1.jsp I use directive <jsp:forward page="page2.jsp">. On the page2.jsp I want to make some action after form submit, but as soon as execute method submit for this form (where is page2.jsp), immediately occurs return on page1.js