Proper Try Catch Format

I have several statements that can throw errors. I currently have nested try statements. Is this the normal way to catch exceptions and is good java coding?
1. ConnectToSQL - could throw SQL Excep
2. Loop Process
a. Get Next Item in ResultSet - could throw SQL Excep
b. Process the info. - could throw standard Excep
My format is:
try{
statement1
}catch(SQL){...}
try{
while(){
statement 2a.......
try{
statement 2b......
}catach{Exc}
}catch{SQL....}

saltzmanjoelh,
That's a good question... (As Paul said:) It all depends on the situation.
If your application is all-about manipulating data stored in the database, you would terminate the app outright if you can't connect to the database. Right? It's stuffed and there's no point in trying to recover (programatically)... Human intervention is required.
But what if the application where a game, and the database was only used to store high scores? Would you terminate the app, or just disable the high-score feature?
So... If you want a real opinion on a real circumstance you're going to have to post the real code, and describe the relevant functional and non-functional business requirements... Ergo: You don' wanna' write it, and I don' wanna read it. <yawn/>.
Use your best judgement... learn from you mistakes.... It gets easier with practice
Cheers. Keith.
Edited by: corlettk on 15/02/2009 23:03 ~~ Premature postage. Ouch!

Similar Messages

  • How do I use try/catch so that it loops until proper input is put in?

    So I have a specific thing that I am asking for (double)... if user inputs letters instead i do try/catch... how do I have it loop until user puts in proper stuff?

    i think i might have figured it out...
              String first = JOptionPane.showInputDialog("Enter the first number");
              while(num1 != double || num1 != int){
              try{
              num1 = Double.parseDouble(first);
              catch (NumberFormatException e){
                   String first = JOptionPane.showInputDialog("Enter the first number");
              }now i need to figure out how to make
    num1 != double || num1 != intpart work..

  • Yet another Try Catch question. Iterating through a ForEach loop

    Confused on error handling in a Powershell ForEach loop. I’m looping through a list of registry keys, attempting
     to open each one. If it succeeds, I do a bunch of stuff. If it fails, I want to skip to the next iteration.
    If I was doing It in VBScript I’d do this:
    For Each Thing In colThings
    Open Thing
    If Err.Number <> 0 Then
    “oops”
    Else
    Do stuff
    Do stuff
    Do stuff
    End If
    Next
    This is what I came up with in PowerShell. It seems to work, but just doesn’t seem powershell-ish. There must be a better way to use the catch output than just creating a $return variable and assigning it success or fail?
    ForEach ($subKeyName in $subKeyNames)
    try{$subKey = $baseKey.OpenSubKey("$subKeyName")}
    catch{$return = "error" }
    If($return -eq "error" )
    “Oops”
    Else
    Do stuff
    Do stuff
    Do Stuff

     
    I totally get what you're saying about formatting. I don't' have any habits yet, since I've only been working in Powershell since... well, what time is it now?
    Unfortunately, It Has Been Decreed that we are no longer to use VBScript for any engineering solutions at work, so my 15 years experience in it now needs to be transitioned over asap. I don't have the luxury of crawling before I run. I'm trying not to be
    frustrated, but it's like an English major waking up one day and being told "You must now speak French exclusively. Here's a book."
    The Do Stuff example of my ForEach loop is about 50 lines of code involving matching values in subkeys of this registry key with another and collecting output. I tried wrapping the whole thing in a try section based on some examples, but it seemed odd, that's
    why I'm asking. I'm used to tightly focused error handling at the point where an error may occur.
    In this example I'm only interested in whether or not I can open the subkey (it exists, but I may not have permission). If I can't, there's no point in continuing with this iteration of the loop, I want to skip to the next one. So why include all the "Do
    Stuff" in the the try section? From a readability viewpoint, it doesn't seem helpful.
    Also, there may be more error handling deeper in the code. If I then put that in a try/catch, and then something else inside that, now I have nested try/catches mixed in with nested if/elses, all wrapped in a For loop.
    Again, I can see how it works logically, but for readability not so much, and having all these braces 50 lines apart to match up is giving me eye strain :).
    It sounds like David is agreeing with jrv, that putting the entire ForEach loop code into a try/catch is the conventional way to do it. I guess it makes as much sense as putting it all in an If-else-Endif, and I just need to adjust my paradigm.
    But if not, my specific question was more along the lines of, is there a built in way to tell that the catch section has been executed, rather than me using it to populate an arbitrary variable and then read it? In VBScript, you execute something, and the
    next line, you check the Err.number. I wasn't sure if you could do that with a try/catch.

  • BufferedWriter try catch Scoping problem

    I developed a quick and dirty application to search through a file system for files that contain certain patterns in their names, and it works fine. My problem is I want to use a BufferedWriter to write the results out to a new text file, and a buffered writer must be enclosed in a try catch statement because of a possible IOException. Now the writer is out of scope of the method that needs to call it, and if I put it in the method a new writer and hence a new file will be created each time through. I am sure this is just a design flaw on my part but I have hit this problem before, I was wondering what is a way around this, so the writer can be instantiated, the method that will do that actual writing to the file will be called until the iteration is done, and then the program will exit.
    Here is my code, there are some unused variables and objects in there, namely I am not using the BufferedWriter at the moment and was just cutting and pasting from the console:
    Thanks!
    import java.io.*;
    import java.util.*;
    public class NextAttempt {
         static List<File> filelist = new ArrayList<File>();
         static PrintStream out = new PrintStream(System.out);
         static File f;
         public static void getWriter() {
              try {
                   BufferedWriter writer = new BufferedWriter(new FileWriter("C:\\FILE.txt"));
                        for(File f: filelist)
                             writer.append(f.getAbsolutePath());
              catch (Exception e) {}
         public static List<File> browse(File BASE) {
              File[] temp=BASE.listFiles();
                   for (int i=0;i<temp.length;i++) {
                        if(temp.getAbsolutePath().contains(File.separator+"PATTERN")&&temp[i].getName().contains(".ext") {     
                             out.println(temp[i].getAbsolutePath());
                             //filelist.add(temp[i]);
                        else if (temp[i].isDirectory()) {
                                  BASE=temp[i];
                                  rec(BASE);
                        else {
                             BASE=new File("PATH");
              return filelist;
         public static void rec(File BASE) {
              browse(BASE);
         public static void main(String[] args) {
              browse(new File("PATH"));
              out.println("Complete");

    Also you can keep passing the file lists up to the callers, so the initial invocation of browse() will return a list of all the files. When you recurse (which you're doing now, apparently), you can append the return value of the recursive call to the caller's own list of files.
    Then just print the whole list when you're done.
    Another thing you might want to think about... you could use the logging framework to list the files as log entries. That may or may not be useful. The advantage is that the logging code already deals with some of these issues; the disadvantage is that producing a formatted log might result in a format you can't use, or tweaking the format might be more trouble than doing something else.

  • Try-catch, new to java

    Anyone know how to effectivly exit a try catch statement if the exception is thrown? Heres this code I'm working with:
    public void create(){
         textCheck1 = textField1.getText();
         try{
           intCheck = Integer.parseInt(textCheck1);
         catch(IllegalArgumentException nfe) {
           System.out.println("NumberFormatException: Level must be a number between 1-70");
         if(intCheck>70){
             throw new NumberFormatException("NumberFormatException: Level must be a number between 1-70");
         else{
           TextArea.setText("Character Successfully Created");
           if(button1.isSelected()){
           System.out.println("Character: \n"+"Name: "+textField2.getText()+"\n"+"Job: "+box.getSelectedItem()+"\n"+"Level: "+textField1.getText()+"\n"+"Gender: Male"+"\n"+"Heroic: "+checkBox.isSelected()+"\n");
           else if(button2.isSelected()){
           System.out.println("Character: \n"+"Name: "+textField2.getText()+"\n"+"Job: "+box.getSelectedItem()+"\n"+"Level: "+textField1.getText()+"\n"+"Gender: Male"+"\n"+"Heroic: "+checkBox.isSelected()+"\n");
        }the way this is set up, when the catch block throws the exception the if-else executes anyway and the results are printed. If the string isn't formated correctly I want to throw the exception and exit the method. please help. thanks.

    cyberjed1 wrote:
    try{
    intCheck = Integer.parseInt(textCheck1);
    catch(IllegalArgumentException nfe) {
    System.out.println("NumberFormatException: Level must be a number between 1-70");
    }the way this is set up, when the catch block throws the exception the if-else executes anyway and the results are printed. If the string isn't formated correctly I want to throw the exception and exit the method. please help. thanks.Two flaws:
    1) You're catching IllegalArgumentException instead of NumberFormatException. The catch would never be entered.
    2) You're ignoring/swallowing the exception and doing a 'dumb' sysout instead of throwing the (new) exception.
    Fix your code as follows:
    try{
        intCheck = Integer.parseInt(textCheck1);
    } catch (NumberFormatException nfe) {
        throw new NumberFormatException("NumberFormatException: Level must be a number between 1-70");
    } Exactly the way as you did in the subsequent if block.
    By the way, if you consider yourself new to Java, why don't you make use of the 'New to Java' forum? Here we expect a bit more from you.

  • PowerShell - Remote Sessions, Try{}Catch{}, ErrorActionPreference

    Hello everyone,
    I am encountering issues with Remote Exchange sessions and was wondering what I am overlooking/over-complicating.
    I am running Windows 8.1/PowerShell 4.0. Reason I mention this is because of this blog post:
    http://blogs.msdn.com/b/powershell/archive/2013/10/25/windows-management-framework-4-0-is-now-available.aspx
    The IMPORTANT section noted that Exchange 2007, 2010, 2013 are not compatible with WMF 4.0 and didn't know if that is good/bad since the OS is using PowerShell 4.0.
    1 - I am connecting to Office 365 utilizing the following:
    http://help.outlook.com/en-us/140/cc952755.aspx
    2 - I have the following function:
    function Get-SomeMailboxStatistics {
    [CmdletBinding()]
    param(
    [Parameter(Mandatory=$True,
    ValueFromPipeline=$True,
    HelpMessage="Identities or aliases to gather Exchange Statistics from.")]
    [Alias('Username')]
    [string[]]$Identity,
    [string]$ErrorLog = 'C:\MbxStatsErrorLog.txt',
    [switch]$LogErrors
    BEGIN{}
    PROCESS{
    Write-Verbose "Beginning..."
    foreach ($alias in $Identity)
    Write-Verbose "Gathering info for $alias."
    #trap [ManagementObjectNotFoundException] {$everythingOK = $false}
    Try{
    # $ErrorActionPreference = "Stop" # Testing purposes.
    $everythingOK = $true
    $gms = Get-MailboxStatistics -Identity $alias -ErrorAction Stop # http://technet.microsoft.com/library/hh847884.aspx
    # Trap {
    # throw $_
    Catch{
    $everythingOK = $false
    Write-Warning "Lookup on $alias failed."
    if ($LogErrors -eq $true){
    $alias | Out-File $ErrorLog -Append
    Write-Warning "Logged $alias to $ErrorLog."
    if ($everythingOK){
    $props = @{};
    $props = @{'Alias' = $alias;
    'DisplayName' = $gms.DisplayName;
    'TotalItemSizeInBytes' = ($gms.TotalItemSize.Value.ToString() -replace "(.*\()|,| [a-z]*\)", "");
    'TotalDeletedItemSizeInBytes' = ($gms.TotalDeletedItemSize.Value.ToString() -replace "(.*\()|,| [a-z]*\)", "");
    'MailboxType' = $gms.MailboxType; };
    $obj = New-Object -TypeName PSObject -Property $props
    Write-Output $obj
    END{}
    Example: Get-SomeMailboxStatistics -Identity GoodAlias1,GoodAlias2,FailAlias,GoodAlias3 -LogErrors -ErrorLog 'C:\Logs\MbxStatsErrors.txt' -Verbose
    The pipeline terminates on FailAlias, and then throws an error when it tries to pass the FailAlias to the $props.
    $gms | Get-Member on a good alias is:
    TypeName: Deserialized.Microsoft.Exchange.Management.MapiTasks.Presentation.MailboxStatistics
    I have tried setting $ErrorActionPreference = 'Stop' in various sections and think I am scope-creeping/not catching the Error where I should be or PowerShell is flat-out ignoring something.
    I have tried additional nested if{}else{} in the Try{}Catch{} and cannot get it to behave as expected.
    I have also tried to Trap{[ManagementObjectNotFoundException]} and Throw exception in various portions without success.
    However, setting $ErrorActionPreference = 'Stop' in the session window (from default of 'Continue') the script behaves as I expected it to, when encountering a non-existant mailbox, it logs the error. It doesn't seem to have issues executing on Windows 8.0/PowerShell
    3.0.
    I have encountered numerous blog/forum posts with no definitive answer/resolution.
    Based some of my tests around some suggestions from this thread:
    http://stackoverflow.com/questions/1142211/try-catch-does-not-seem-to-have-an-effect
    Extras:
    http://blogs.technet.com/b/heyscriptingguy/archive/2010/03/09/hey-scripting-guy-march-9-2010.aspxhttp://stackoverflow.com/questions/19553278/powershell-catch-non-terminating-errors-with-silentlycontinue
    http://stackoverflow.com/questions/15545429/erroractionpreference-and-erroraction-silentlycontinue-for-get-pssessionconfigur
    http://social.technet.microsoft.com/Forums/scriptcenter/en-US/228a3329-f564-4daa-ad70-6d869b912246/non-terminating-error-turned-into-a-terminating-error?forum=winserverpowershell

    This is not the only problem with WMF 4.0
    When you use -ErrorAction 'SilentlyContinue', $Error object is not set.
    [PS]
    $Error.Clear()
    [PS]
    $objContact =
    Get-Contact -Identity
    'CN=unknown contact,OU=Users,DC=mydomain,DC=mytopdomain'
    -ErrorAction 'Stop'
    The operation couldn't be performed because object 'mytopdomain.mydomain/Users/unknown contact' couldn't be found on 'mydc.mydomain.mytopdomain'.
        + CategoryInfo          : NotSpecified: (:) [Get-Contact], ManagementObjectNotFoundException   
    + FullyQualifiedErrorId : 482E7079,Microsoft.Exchange.Management.RecipientTasks.GetContact
        + PSComputerName        : myexchange.mydomain.mytopdomain
    [PS]
    $Error.Count
    1
    [PS]
    $Error.Clear()
    [PS]
    $objContact =
    Get-Contact -Identity
    'CN=unknown contact,OU=Users,DC=mydomain,DC=mytopdomain'
    -ErrorAction 'SilentlyContinue'
    [PS]
    $Error.Count
    0
    That's why since Exchange 2010 SP3 Rollup 5 (i suppose when reading Exchange Supportability Matrix), The Exchange Management Shell link has been updated to use Powershell 2.0
    Before 2010 SP3 Rollup 5
    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"
    After 2010 SP3 Rollup 5
    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -version 2.0 -noexit -command ". 'C:\Program Files\Microsoft\Exchange Server\V14\bin\RemoteExchange.ps1'; Connect-ExchangeServer -auto"

  • How to simulate a dml error in order to test try-catch code block inside a stored procedure

    Hi,
    What would be the easiest way to simulate a dml error in order to test a try catch block.
    I would like to do it with a simple command from outside the stored procedure if possible.
    I tried dropping the table that was updated but it hangs
    Thanks,
    Dani

    Dropping the table that is the target of the procedure will give you an unpleasant surprise: the CATCH block will not fire. To wit, errors like missing tables can only be caught in outer scopes, but not in the procedure where the error occurs.
    But you would add a fake constraint to a table which causes the update to fail. You need to do this in advance, not while running the procedure.
    Erland Sommarskog, SQL Server MVP, [email protected]

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

  • When I try to format an external usb drive  the progress bar only goes half way then freezes up can anybody help please

    When I try to format an external usb drive  the progress bar gets to half way then freezes , or stops and  what ever time I allow it never gets any futher on , I have to go to the task bar and click quit  to get on  and the usb drive is not formatted  is there a fault with my disk utility program  I have updated the system
    to lion 10.7.2
    Can anybody advise please

    Are these new external drives? How are the currently formatted? Have you tried doing this:
    Drive Preparation
    1. Open Disk Utility in your Utilities folder.
    2. After DU loads select your hard drive (this is the entry with the mfgr.'s ID and size) from the left side list. Click on the Partition tab in the DU main window.
    3. Under the Volume Scheme heading set the number of partitions from the drop down menu to one. Set the format type to Mac OS Extended (Journaled.) Click on the Options button, set the partition scheme to GUID then click on the OK button. Click on the Partition button and wait until the process has completed.
    4. Select the volume you just created (this is the sub-entry under the drive entry) from the left side list. Click on the Erase tab in the DU main window.
    5. Set the format type to Mac OS Extended (Journaled.) Click on the Security button, check the button for Zero Data and click on OK to return to the Erase window.
    6. Click on the Erase button. The format process can take up to several hours depending upon the drive size.
    Steps 4-6 are optional but should be used on a drive that has never been formatted before, if the format type is not Mac OS Extended, if the partition scheme has been changed, or if a different operating system (not OS X) has been installed on the drive.

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

  • RAISERROR with Try/Catch does not exit after exception in catch block

    I am trying to propogate an error from within my proc out to the caller.
    In the attached example I have 2 sets of try catch blocks.
    I raiserror in the first
    catch the error and then raiserror again. (I expect to exit)
    I do not expect :
    to get to print 'post test'
    to get to second try block.
    but this does not exit, instead the code flows as per 2 runs.
    I do not understand the reason for the flows, as it seems counterintuitive to be raising an error but then still print following exceptions. I cannot seem to find any references that explains this behaviour.
     running tests together results
    print '-------------------------------------------------------'
    print 'test 15'
    exec test_raiseerror 15
    print '-------------------------------------------------------'
    print 'test 16'
    exec test_raiseerror 16
    print '-------------------------------------------------------'
    print 'test 17'
    exec test_raiseerror 17
    print '-------------------------------------------------------'
    print 'test 18'
    exec test_raiseerror 18
    print '-------------------------------------------------------'
    'RESULTS'
    test 15
    error number provided: 15
    Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 21
    name hello 15
    post test
    15
    Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 37
    name hello 2 15
    post test2
    test 16
    error number provided: 16
    Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 21
    name hello 16
    post test
    16
    Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 37
    name hello 2 16
    post test2
    test 17
    error number provided: 17
    post test
    17
    post test2
    test 18
    error number provided: 18
    post test
    18
    post test2
    Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 21
    name hello 17
    Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 37
    name hello 2 17
    Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 21
    name hello 18
    Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 37
    name hello 2 18
    run tests seperately
    exec test_raiseerror 15
    error number provided: 15
    RESULTS 15
    Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 21
    name hello 15
    post test
    15
    Msg 50000, Level 15, State 1, Procedure test_raiseerror, Line 37
    name hello 2 15
    post test2
    exec test_raiseerror 16
    RESULTS 16
    error number provided: 16
    Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 21
    name hello 16
    post test
    16
    Msg 50000, Level 16, State 1, Procedure test_raiseerror, Line 37
    name hello 2 16
    post test2
    exec test_raiseerror 17
    RESULTS 17
    error number provided: 17
    post test
    17
    post test2
    Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 21
    name hello 17
    Msg 50000, Level 17, State 1, Procedure test_raiseerror, Line 37
    name hello 2 17
    exec test_raiseerror 18
    RESULTS 18
    error number provided: 18
    post test
    18
    post test2
    Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 21
    name hello 18
    Msg 50000, Level 18, State 1, Procedure test_raiseerror, Line 37
    name hello 2 18
     CODEBLOCK:
    if object_id('test_raiseerror','P') is not null
    drop proc test_raiseerror
    go
    create proc test_raiseerror(@id as int) as
    begin
    begin try
    declare @name varchar(20)
    select @name = 'hello'
    raiserror('name %s %d',@id,1,@name,@id)
    print 'next'
    end try
    begin catch
    declare @errormessage nvarchar(4000)
    declare @errornum int
    select @errormessage = error_message()
    , @errornum = error_severity()
    print 'error number provided: ' + convert(varchar(2),@errornum)
    raiserror(@errormessage, @errornum,1)
    print 'post test'
    end catch
    begin try
    select @name = 'hello 2'
    raiserror('name %s %d', @id,1,@name, @id)
    end try
    begin catch
    select @errormessage = error_message()
    , @errornum = error_severity()
    print @errornum
    raiserror(@errormessage, @errornum,1)
    print 'post test2'
    end catch
    end
    go
    sqlserver 2008 & 2008 R2

    There is a Connect that describes a similiar complaint.  But basically a raiserror inside a catch block does not terminate the procedure, it will continue with any additional code in the CATCH and FINALLY unless it hits a return statement.
    http://connect.microsoft.com/SQLServer/feedback/details/275308/have-raiserror-work-with-xact-abort

  • Exception handling with try/catch in acrobat

    Hi
    I have a problem using a try/catch block in my acrobat document-script. Try to enter the following into the debugger-console:
    try{nonexistentFunction();}catch(e){console.println('\nacrobat can't catch')}
    and run it. The output will be:
    nonexistentFunction is not defined
    1:Console:Exec
    acrobat can't catch
    true
    The whole point of a rty/catch block is for the application  NOT to throw an exception, but instead execute the catch-part of the  statement. However, acrobat does both: It throws an exception AND  executes the catch-block.
    Is there another way to suppress the exception, or to make the try/catch-block work as it's supposed to?

    > Also Adobe provides for free the JS or compiled file for Acrobat Reader to support the JS console.
    Where is that file located ? How to install it or where to place it ?
    What is the method referred by try67 on his site where he sells a product ?
    Is that the same as the compiled file you refer to ? or did he sell his solution to adobe ?
    It is helpful if people can get an idea of the nature of choices available and make informed decisions, than a cloak and dagger approach.
    For some jobs that we have, I have been very frustrated by a consultant who wont even give basic info for transparent billing despite all assurances for privacy, as a result we are forced to do the job ourselves.
    Dying Vet

  • About the finally block of the try catch.

    I know that finally block contains the code that will be executed in any condition of the try catch.
    However, I think it is unneccessary, since the stack after the try catch stack will be executed any way.
    Any one can help?
    for example
    try{
    System.in.read();
    catch(Exception e){}
    finally
    { System.out.println("does this matter?");}and
    try{
    System.in.read();
    catch(Exception e){}
    System.out.println("does this matter?");

    However, I think it is unneccessary, since the stackafter the try catch
    stack will be executed any way.That does assume that you catch and handle the error
    appropriately.
    Of course this is valid as well, and demonstrates
    when you would WANT a finally clause.
    Connection con = null;
    Statement stmt = null;
    try{
    con  = Database.getConnection();
    stmt = con.createStatement("Select * from dual");
    // maybe something throws an exception here?
    finally{
    if (stmt != null){
    stmt.close();
    if (con != null){
    con.close();
    The finally block here might throw a null pointer exception itself use
    null!=stmt null!=stmt

  • Return statement should put beyond try/catch clause??

    The return statement should put beyond the try/catch clause, is that correct? Well,
    I tried to put inside the try block, but it will have compile error though.
    public String getValue()
         String value;
         try
         catch(...)
         return value;
    please advise. thanks!!

    When a method returns a value, you must make sure that even if an exception is thrown and caught a value will be returned (or just throw the exception out of the method).
    You can put a return clause as the last thing in the try block and another return clause after the catch block (this is where we go if we catch an exception so you probably want to return null).

Maybe you are looking for

  • Copy PO Number from contract to sales order

    Hi, My clients requirement is that when i create sales order with reference to contract the PO Number should be copied from contract to sales order other wise we have to enter PO Number every time while creating the sales order. Please guide me.

  • Import data backup into another DB instance

    Hello all. I need to import a Data Backup into Another Database instance. MaxDb version 7.3. On higher versions of MaxDb I performed this operation without any problems (http://help.sap.com/erp2005_ehp_04/helpdata/EN/43/d5ebc2c9ed3ab3e10000000a422035

  • The 'java.lang.InterruptedException' error when the batch  running

    Hello everyone: hope everyone go well in your CC&B project. We have an obstacle we we run some bacth job(not all the time), the log is as following: 03:36:46,060 [DEFAULTWorker:7] ERROR (com.splwg.base.support.batch.GenericCobolBatchProgram) Unexpect

  • End Point Error with Azure Cloud Service

    Hey Guys, I have created a Cloud Service and want to access in my windows 8 store app, But during call the i am getting error like below  There was no endpoint listening at http://batlas2.cloudapp.net/AtlasCloudService.svc that could accept the messa

  • How do you auto center page vertically?

    I'm using DW CS4, Mac. I have created a template web page with the exact size of 1000-pixels wide, by 600-pixels tall. I was easily able to set the page to automatically center itself widthwise in the browser. However, I have no idea how to make it d