How to use Try Catch Block in ABAP Like JAVA

Hi Experts,
   I am using BAPI to post MIGO in one of my application. If the MIGO is successfully gets posted then BAPI returns no message, but if there is some error in posting then it returns an error message. Now I want to print that error message in catch block by calling method RAISE_ERROR_MESSAGE. How to use try catch block in ABAP. Please suggest with example.
Thanks and Regards.
Vaibhav Tiwari.

Hi Vaibhav
You may not catch exceptions returned by function module using try endtry block.
It works well with the exception returned by methods.
In case of function modules or BAPI what u can do is to check sy-subrc returned and give message accordingly. If it returns a structure like bapireturn then display message returned.
in case of exception returned by a method,  do it like this...
data: excep type cx_root.
data: v_str type string.
try.
*any method call or division by zero (for ex)
catch cx_root into excep.
endtry.
if  excep is not initial.
CALL METHOD   excep->if_message~get_text
  receiving
    RESULT = v_str.
endif.
*display the value returned in v_str on screen

Similar Messages

  • Try-catch blocks.  How do you get variables out?

    Hey guys,
    I have several try-catch blocks around potential NumberFormatException's. Well the variables and values given inside the try-catch block can not be used outisde, so how do i get them out or use them outside this block.
    Is there a way to kind of pass it out, or to take the variable outside the try-catch block?
    Gary.

    Declare the variable before the try block:
    public void foo(String number) {
    int i; // Unknown
    try {
    i = Integer.parseInt(number);
    } catch( NumberFormatException e ) {
    e.printStackTrace();
    System.out.println(i);
    variable i might not have been initialized
                   System.out.println(i);
                                      ^
    Or declare the method as throwing the exception so
    that you don't have to handle it directly
    public void foo(String number)
    throws NumberFormatException
    i = Integer.parseInt(number);
    System.out.println(i);
    }Not the best example, in this case. But it works for some things.
    Or make use of the variable within the try block so
    that you limit its scope to the degree possible
    public void foo(String number) {
    try {
    i = Integer.parseInt(number);
    System.out.println(i);
    } catch( NumberFormatException e ) {
    e.printStackTraceException();
    }Definitely missed declaring i, but I like this one best ;~)
    Each has its benefits. Depends what sort of method
    you're writing - if failure of the try block causes
    the whole method to fail, don't try to handle the
    exception locally, put the throws in the signature. ~Cheers

  • Performance impact on using too much try catch block

    I have several questions here:
    1. The system that I'm developing requires to be high performance, but I am not sure how will try catch block affect overall performance.
    2. I wanted to know which would be more efficient (result in faster processing)
    Have several generic try catch OR catch all exceptions individually?
    ex:
    try {
    } catch (Exception e){
    }vs.
    try{
    } catch (MalformedUrlException me){
    } catch(SQLException){
    }3. Which one would be faster, one big try catch block or several small try catch blocks?
    ex.
    try{
    //read from io file
    //query database
    //parse data
    //write to file
    //query database again
    } catch(Exception e){
    //log exception
    }vs.
    try{
    //read from io file
    } catch(FileNotFoundException fnfe){
    //log exception
    try{
    //query database
    }catch(SQLException se){
    //log exception
    try{
    //parse data
    }catch(SaxParserException saxe){
    //log exception
    try{
    //query database again
    }catch(SQLException se2){
    //log exception
    try{
    //write to file
    } catch(FileNotFoundException fnfe){
    //log exception

    1. The system that I'm developing requires to be high performance, but I am not sure how will try catch block affect overall performance.Compared to what? You can't write an equivalent program that doesn't have a try-catch block, so the answer would have to be that it doesn't affect performance at all.
    2. I wanted to know which would be more efficient (result in faster processing)Have several generic try catch OR catch all exceptions individually?
    You still have it backwards. Do you need to do different things for different exceptions? If so, then that's what you have to do and there is no other code that might be "faster".
    Here's what you should do. Write the code that needs to be written. Don't leave out necessary stuff because of performance reasons. (If you left out all your code, the program would run much faster.) Then find out which parts of the program ACTUALLY take the most time and work on speeding them up.

  • How to get the returned error messages in the Try/Catch block in DS 3.0?

    A customer sent me the following questions when he tried to implement custom error handling in DS 3.0. I could only find the function "smtp_to" can return the last few lines of trace or error log file but this is not what he wants. Does anyone know the answers? Thanks!
    I am trying to implement the Try/Catch for error handling, but I have
    hard time to get the return the msg from DI, so I can write it to out
    custom log table.
    Can you tell me or point me to sample code that can do this, also, can
    you tell me which tables capture these info if I want to query it from
    DI system tables

    Hi Larry,
    In Data Services XI 3.1 (GAd yesterday) we made several enhancements for our Try/Catch blocks. One of them is the additional of functions to get details on the error that was catched :
    - error_message() Returns the error message of the caught exception
    - error_number() Returns the error number of the caught exception
    - error_timestamp() Returns the timestamp of the caught exception.
    - error_context() Returns the context of the caught exception. For example, "|Session Datapreview_job|Dataflow debug_DataFlow|Transform Debug"
    In previous versions, the only thing you could do was in the mail_to function specify the number of lines you want to include from the error_log, which would send the error_log details in the body of the mail.
    Thanks,
    Ben.

  • Can't find class because of try catch block ?!

    Hello,
    I'm using the JNI to use a java library from my c++ code.
    JNI can't find the "Comverse10" class below, but when i put the try catch block in createMessage in comment, FindClass succeeds ?!
    Unfortunatly i need the code inside the try block ;-)
    I tried a few things, but none of them worked:
    - let createMessage throw the exception (public void createMessage throws ElementAlreadyExistsException ), so there isn't a try catch block in createMessage => result: the same
    - make a "wrapper" class Comverse that has a Comverse10 object as attribute and just calls the corresponding Comverse10.function. Result: Comvers could be found, but not constructed (NewObject failed).
    Can someone tell me what is going on ?!
    Thank you,
    Pieter.
    //Comverse10 class
    public class Comverse10 {
    MultimediaMessage message;
    /** Creates a new instance of Comverse10 */
    public Comverse10() {
    public void createMessage() {
    TextMediaElement text1 = new TextMediaElement("Pieter");
    text1.setColor(Color.blue);
    SimpleSlide slide1 = new SimpleSlide();
    //if i put this try catch block in comment, it works ?!
    try{
    slide1.add(text1);
    catch(com.comverse.mms.mmspade.api.ElementAlreadyExistsException e){}
    MessageContent content = new MessageContent();
    content.addSlide(slide1);
    this.message = new MultimediaMessage();
    message.setContent(content);
    message.setSubject("Mijn subjectje");
    for those of you who are intersted: here's my C++ code:
    //creation of JVM
    HRESULT Java::CreateJavaVMdll()
         HRESULT HRv = S_OK;
    char classpath[1024];
         jint res;
         if(blog)     this->oDebugLog->Printf("CreateJavaVMdll()");
         strcpy(classpath,"-Djava.class.path="); /*This tells jvm that it is getting the class path*/
         strcat(classpath,getenv("PATH"));
         strcat(classpath,";D:\\Projects\\RingRing\\MMSComposer;C:\\Progra~1\\j2sdk1~1.1_0\\lib");     //;C:\\Comverse\\MMS_SDK\\SDK\\lib\\mail.jar;C:\\Comverse\\MMS_SDK\\SDK\\lib\\activation.jar;C:\\Comverse\\MMS_SDK\\SDK\\lib\\mmspade.jar
         //------Set Options for virtual machine
         options[0].optionString = "-Djava.compiler=NONE"; //JIT compiler
         options[1].optionString = classpath;                                        //CLASSPATH
         //------Set argument structure components
         vm_args.options = options;
         vm_args.nOptions = 2;
         vm_args.ignoreUnrecognized = JNI_TRUE;
         vm_args.version = JNI_VERSION_1_4;
         /* Win32 version */
         HINSTANCE hVM = LoadLibrary("C:\\Program Files\\j2sdk1.4.1_01\\jre\\bin\\client\\jvm.dll");
         if (hVM == NULL){
              if(blog) oDebugLog->Printf("Can't load jvm.dll");
              return E_FAIL;
         if(blog) oDebugLog->Printf("jvm.dll loaded\n");
         LPFNDLLFUNC1 func = (LPFNDLLFUNC1)GetProcAddress(hVM, "JNI_CreateJavaVM");
         if(!func){
              if(blog)     oDebugLog->Printf("Can't get ProcAddress of JNI_CreateJavaVM");
              FreeLibrary(hVM);     hVM = NULL;
              return E_FAIL;
         if(blog)     oDebugLog->Printf("ProcAddress found");
         res = func(&jvm,(void**)&env,&vm_args);
         if (res < 0) {
    if(blog)     oDebugLog->Printf("Can't create JVM with JNI_CreateJavaVM %d\n",res);
    return E_FAIL;
         if(blog)     oDebugLog->Printf("JVM created");
         return HRv;
    //finding Comverse10 class:
    HRESULT CALLAS MMSComposer::InitializeJNI(void)
         HRESULT HRv=E_FAIL;
         DWORD T=0;
         try
              if(blog)     oDebugLog->Printf("\nInitializeJNI()");
              bJVM = FALSE;
              jni = new Java(oDebugLog);
              if(jni->CreateJavaVMdll()!=S_OK){
                   if(blog)     oDebugLog->Printf("CreateJavaVMdll() failed");     
                   return HRv;
              jclass jcls = jni->env->FindClass("Comverse10");
              if (jcls == 0) {
    if(blog)     oDebugLog->Printf("Can't find Comverse10 class");
                   jclass jcls2 = jni->env->FindClass("test");
                   if (jcls2 == 0) {
                        if(blog)     oDebugLog->Printf("Can't find test class");
                        return HRv;
                   if(blog)     oDebugLog->Printf("test class found %08x",jcls2);
    return HRv;
              if(blog)     oDebugLog->Printf("Comverse10 class found %08x",jcls);
              jmethodID mid = jni->env->GetMethodID(jcls , "<init>", "()V");
              if (mid == 0) {
                   if(blog)     oDebugLog->Printf("Can't find Comverse10() constructor");
    return HRv;
              if(blog)     oDebugLog->Printf("Comverse10() constructor found");
              jobject jobj = jni->env->NewObject(jcls,mid);
              if(jobj==0)
                   if(blog)     oDebugLog->Printf("Can't construct a Comverse10 object");
    return HRv;
              if(blog)     oDebugLog->Printf("Comverse10 object constucted");
              //Create Global reference, so java garbage collector won't delete it
              jni->jobj_comv = jni->env->NewGlobalRef(jobj);
              if(jni->jobj_comv==0)
                   if(blog)     oDebugLog->Printf("Can't create global reference to Comverse10 object");
    return HRv;
              if(blog)     oDebugLog->Printf("global reference to Comverse10 object %08x created",jni->jobj_comv);
              bJVM=TRUE;
              HRv=S_OK;
         }     catch( IDB * bgError ) { throw bgError->ErrorTrace("InitializeJNI::~InitializeJNI",HRv, 0, T); }
              catch(...) { throw IDB::NewErrorTrace("InitializeJNI::~InitializeJNI",HRv, 0, T ); }
              return HRv;

    >
    I would guess that the real problem is that that the
    exception you are catching is not in the class path
    that you are defining.Thanks jschell, that was indeed the case.
    I don't have the docs, but I would guess that
    FindClass() only returns null if an exception is
    thrown. And you are not checking for the exception.
    Which would tell you the problem.Ok, i'll remember that. But what with exceptions thrown in my java code, the documents say
    // jthrowable ExceptionOccurred(JNIEnv *env);
    // Determines if an exception is being thrown. The exception stays being thrown until either the native code calls ExceptionClear(), or the Java code handles the exception
    so, what if the java code throws an exception and catches it, will i be able to see that in my c++ code with ExceptionOccurred ?
    or
    should the java method be declared to throw the exception (and not catch it inside the method)
    Again, thank you for your help, it's greatly appreciated !

  • Try Catch Blocks

    This may be too vague of a question but is it bad practice to use one large try catch block? In my mind it seems like it would produce "cleaner" code as far as programmer reading is concerned, but does it affect the program adversely?
    try {
    // code goes here
    } catch (somekindofexception e){
    // print exception e
    } catch (anotherkindofexception e){
    // print exception e
    } // continue for all possible exceptions

    bolivartech wrote:
    I was mistaken it looks like the particular function I was thinking of throws 3 kinds of RuntimeExceptions, but the same idea applies right?
    try {
    } catch (RuntimeException e) {
    System.err.println("Caught RuntimeException: " +  e.getMessage());
    Yes, you can do that if you want to handle all of them the same.
    However, if you want to handle different exceptions differently, you'd catch those specific exceptions, rather than the parent exception type. This is a separate issue from whether you have one big try or lots of little trys.
    NOTE HOWEVER THAT YOU SHOULD NOT CATCH RuntimeException OR ITS DESCENDANTS. RuntimeException indicates an error in your code. Catching it is usually pointless, because you can't recover from it, and trying to continue on will probably lead to corrupt results at best.

  • Error when using try catch inside oledb command to run stored procedure

    Hi,
    i'm using the below command to run some jobs  using OLEDB Command
    exec sp_start_job @job_name =?
    and it runs successfully
    when i put this code inside try catch block as below , it generates error and don't accept it
    begin try
    exec sp_start_job @job_name =?
    end try
    begin catch
    end catch
    the error message is "Syntax error, PErmission vaiolation or other nonspecific error"
    do you know is there any problem using TRY catch insdie OLEDB command ?
    Thanks ,
    Ahmed Salah

    Hi Ahmed,
    According to your description, if an error raised that fails the package, then you want the package to continue execute.
    To achieve this requirement, we can use Integration Services (SSIS) Event Handlers that we can create custom event handlers for an OnError event when an error occurs to continue processing rest of the package. For more details, please refer
    to the following blog:
    http://visakhm.blogspot.in/2013/03/error-handling-in-ssis-loops.html
    If there are any other questions, please feel free to ask.
    Thanks,
    Katherine Xiong
    Katherine Xiong
    TechNet Community Support

  • How to use this function module on abap hr GET_PDSNR_RANGE

    how to use this function module on abap hr GET_PDSNR_RANGE
    thankx.

    PASS INETRNAL TABLE WITH SOME DATA TO TABELLE FOR GENERATING PDSNR SEQUENCE

  • How to use the SQVI in HR-ABAP

    Dear Guru,
    How to use Quick Viewer in HR ABAP,
    kindly give some sample materials for this .
    else provide some soluytion for this .
    Regards,
    Mathankumar.A

    I don't think there is any difference when comes to HR ABAP. so you can proceed the way you do incase of normal tables. the only difference here is you will see Infotypes  instead of Tables.

  • [svn:fx-3.x] 10953: Get rid of a try/ catch block that was generating a lot of noise on the heap.

    Revision: 10953
    Author:   [email protected]
    Date:     2009-10-09 10:50:37 -0700 (Fri, 09 Oct 2009)
    Log Message:
    Get rid of a try/catch block that was generating a lot of noise on the heap.
    QE Notes: None
    Doc Notes: None
    Bugs: SDK-23563
    Reviewer: Ryan
    API Change: no
    Is noteworthy for integration: No
    tests: checkintests mustella/Managers/DragManager
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-23563
    Modified Paths:
        flex/sdk/branches/3.x/frameworks/projects/framework/src/mx/managers/dragClasses/DragProxy .as

    Revision: 10953
    Author:   [email protected]
    Date:     2009-10-09 10:50:37 -0700 (Fri, 09 Oct 2009)
    Log Message:
    Get rid of a try/catch block that was generating a lot of noise on the heap.
    QE Notes: None
    Doc Notes: None
    Bugs: SDK-23563
    Reviewer: Ryan
    API Change: no
    Is noteworthy for integration: No
    tests: checkintests mustella/Managers/DragManager
    Ticket Links:
        http://bugs.adobe.com/jira/browse/SDK-23563
    Modified Paths:
        flex/sdk/branches/3.x/frameworks/projects/framework/src/mx/managers/dragClasses/DragProxy .as

  • Nested try-catch blocks

    Hello All,
    If I have 2 nested try-catch blocks see below
    try{
        //Some code
        try{
            //Code that throws an IOException
        }catch(NumberFormatException nfe){
            //Handle the NFE
    }catch(Exception e){
        //Handle the Exception
    }Now what happens if in the inner try-catch an IOException is thrown? Will it be ignored, or will it get thrown out to the outer one and be caught by that catch?
    Thanks,
    Matt

    Thanks, should have just done this from the start, but here is the result...
    The following code
    public class Main {
         public void execute(){
              try{
                  try{
                       for(int i=0;i<100;i++){
                            System.out.println(i);
                            if(i==5){
                                 throw new java.io.IOException();
                  }catch(NumberFormatException nfe){
                     System.out.println("caught in inner block");
              }catch(Exception e){
                  //Handle the Exception
                 System.out.println("caught in outer block");
         public static void main(String[] args) {
              Main m = new Main();
              m.execute();
    }GENERATES:
    0
    1
    2
    3
    4
    caught in outer block
    Thanks,
    Matt

  • Compile time errors for large code in try-catch blocks

    Hi, Has anyone ever faced this problem of a compile time error, where the Java compiler returns with the following error that Code is too large for try block.
    I have about 5000 thousand lines in my try-catch block and am facing this problem. Please suggest possible solutions

    1) Are you sure that your try/catch blocks contain 5 million lines?! I seriously don't believe this.Sounds like generated code. The generator needs to be a bit cleverer. In particular, it seems to be generating repeated blocks of code that ought to be stuffed into methods somewhere.

  • Do I always need to use try/catch? [ newbie ]

    Hi,
    I have a method called methodOne that throws ExceptionXXX, and another method called methodTwo that uses methodOne and also throws ExceptionXXX.
    public static methodOne() throws ExceptionXXX
    Does methodTwo need to use try/catch to catch ExceptionXXX from methodOne, ( like the following code )
    public static methodTwo() throws ExceptionXXX
    try
    methodOne();
    catch( ExceptionXXX theException )
    throw new ExceptionXXX;
    or it isn't necessary ( like this code )?
    public static methodTwo() throws ExceptionXXX
    methodOne();
    Thanks for the help,
    Andre

    Hi,
    if you call a mthod w/ a throws declaration you hace two possibilities:
    1. catch the Exception
    2. pass the Exception by adding a throws declaration to the calling method
    So, in your case the second example is a valid way to handle the Exception.
    Also Andre

  • How to use select options whitout ranges ie like parameter

    how to use select options whitout ranges ie like parameter and pls send me the code on that
    thanks
    raja.

    hi,
    SELECT-OPTIONS : s_kunnr for kna1-kunnr <b>no intervels.</b>
    eg: code
    <b>SELECT-OPTIONS : s_kunnr for kna1-kunnr <b>no intervels.</b></b>
    data: itab type table of kna1 with header line.
    select * from kna1 into table itab where kunnr IN s_kunnr.
    rgds
    Anver

  • How to use line wrapping and line spacing in java?how to use line wrapping

    how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?how to use line wrapping and line spacing in java?

    Hello,
    You should post your question at:
    http://java.forum.sun.com
    Thanks
    - Rose

Maybe you are looking for