336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

보통 Try, Catch 문이라고 하면 이런식으로 쓰게 될 것입니다.

void function()
{
    Try
    {
    }
    Catch
    {
        Throw;
    }
}

하지만 throw 를 하게 되면 내부적으로 다소 많은 부하가 걸릴 수 있다고 합니다.
(이 부분에 대해서 개발 실장님께 들었는데 정확한 정보는 찾아보지 못했습니다. 찾게 되면 추가적으로 내용을 쓰도록 하겠습니다.)
그래서 대신에 이런 식으로 처리하면 어떨까 합니다.

void function()
{
    do // dummy do
    {
        // 여기가 try
        if(오류) break;
        if(오류) break;

        // 오류에 걸리지 않았다면 처리
        return;
    } while(false)
    // 여기가 catch
    ERROR("오류가 났습니다.");
}

특히 서버 같은 경우 최적화가 매우 중요하므로,
특별한 상황이 아니라면 throw 를 이용하지 않는 것이 좋지 않을까 생각합니다.

do 든 while 이든 자주 사용하는 것이지만, '이런 식으로 응용을 할 수 있구나' 라고
생각하게 되는 좋은 예제라고 생각합니다.


출처 : http://www.dingpong.net/tt/8?category=2

Posted by 역시인생한방
,
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

未处理 System.InvalidOperationException

  Message=无法关闭撤消单元,因为不存在已打开的单元。


  Source=PresentationFramework

  StackTrace:

       在 MS.Internal.Documents.UndoManager.Close(IParentUndoUnit unit, UndoCloseAction closeAction)

       在 System.Windows.Documents.ImmComposition.CloseCompositionUndoUnit(UndoCloseAction undoCloseAction, ITextPointer compositionEnd)

       在 System.Windows.Documents.ImmComposition.UpdateCompositionText(FrameworkTextComposition composition, Int32 resultLength, Boolean includeResultText, ITextPointer& start, ITextPointer& end)

       在 System.Windows.Documents.ImmComposition.RaiseTextInputStartEvent(FrameworkTextComposition composition, Int32 resultLength, String compositionString)

       在 System.Windows.Documents.ImmComposition.OnWmImeChar(IntPtr wParam, Boolean& handled)

       在 System.Windows.Documents.ImmComposition.ImmCompositionFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

       在 System.Windows.Interop.HwndSource.PublicHooksFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

       在 MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)

       在 MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)

       在 System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)

       在 MS.Internal.Threading.ExceptionFilterHelper.TryCatchWhen(Object source, Delegate method, Object args, Int32 numArgs, Delegate catchHandler)

       在 System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Int32 numArgs)

       在 MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)

       在 MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)

       在 MS.Win32.HwndSubclass.DefWndProcWrapper(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)

       在 MS.Win32.UnsafeNativeMethods.CallWindowProc(IntPtr wndProc, IntPtr hWnd, Int32 msg, IntPtr wParam, IntPtr lParam)

       在 MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)

       在 MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)

       在 System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)

       在 System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)

       在 System.Windows.Application.RunDispatcher(Object ignore)

       在 System.Windows.Application.RunInternal(Window window)

       在 System.Windows.Application.Run(Window window)

       在 System.Windows.Application.Run()

       在 LiveChainCHIS_Client.App.Main() 位置 D:\项目\LiveChainCHIS-Client\LiveChainCHIS-Client\obj\x86\Debug\App.g.cs:行号 0

       在 System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)

       在 System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)

       在 Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()

       在 System.Threading.ThreadHelper.ThreadStart_Context(Object state)

       在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)

       在 System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)

       在 System.Threading.ThreadHelper.ThreadStart()

  InnerException: 


补充说明一下 ,这个错误只出现于 数据绑定后的TextBox控件上。



解决办法:  设置Textbox的UndoLimit 为0就ok。


중문 윈도우에서 중문 IME를 이용해 TextBox에 글자를 입력하려고 하면 발생하는 예외 처리 방법

위에 써있듯이 TextBox에 UndoLimit을 0으로 설정해주면 해결된다


출처 : http://www.cnblogs.com/muzizongheng/p/3169812.html

Posted by 역시인생한방
,
336x280(권장), 300x250(권장), 250x250, 200x200 크기의 광고 코드만 넣을 수 있습니다.

예전에, .NET 응용 프로그램에서 예외 처리를 하는 방법에 관해 정리해놓았지요. ^^

.NET 예외 처리 정리 
; http://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&detail=1&wid=316

WPF - 전역 예외 처리 
; http://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&detail=1&wid=614


WPF로 오면서는 유독 First-chance Exception을 구분하는 것이 더 중요해졌습니다. 일례로 아래와 같은 경우들이 모두 "First-chance exception"을 모르면 문제를 해결하는 데 헤멜수가 있습니다.

예외 처리를 방해하는 WPF Modal 대화창
; http://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&detail=1&wid=619

WPF - XamlParseException 대응 방법
; http://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&detail=1&wid=622


다시 한번 강조하지만, "First-chance Exception"에 대해서 아직도 모르시는 분들은 부디 이번 기회에 꼭 알고 넘어가시기 바랍니다.

First-Chance Exception
; http://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&detail=1&wid=510





WPF에서, 예외 처리에 관해 어려움을 겪는 경우가 하나 더 있는데요. 아래의 코드를 보면서 설명해 보겠습니다.

public partial class Window1 : Window, INotifyPropertyChanged
{
    string name2;
    public string Name2
    {
        get { return this.name2; }
        set 
        {
            this.name2 = value;
            OnPropertyChanged("Name2");
            throw new ApplicationException("TEST");
        }
    }

    private void Window_Loaded(object sender, RoutedEventArgs e)
    {
        this.Name2 = "TEST";
    }
}


보통 위와 같은 상황에서, Visual Studio는 아래와 같이 정상적으로 디버그 지점을 잘 잡아냅니다.

[그림 1: ApplicationException 예외]
not_catch_databind_exception_1.png

하지만, 명시적으로 사용한 this.Name2 = "TEST" 코드를 삭제하고, 대신에 Name2 속성을 데이터바인딩으로 연결하면,

<TextBox Height="30" Margin="16,40,124,0" 
         Text="{Binding Path=Name2}"
/>


이제는 더 이상 Visual Studio IDE에서 예외를 잡아내지 못합니다. 단지 "Output"창에 다음과 같은 식으로 오류 로그가 출력될 뿐입니다.

A first chance exception of type 'System.ApplicationException' occurred in WpfApplication1.exe
A first chance exception of type 'System.Reflection.TargetInvocationException' occurred in mscorlib.dll
System.Windows.Data Error: 8 : Cannot save value from target back to source. BindingExpression:Path=Name2; DataItem='Window1' (Name=''); target element is 'TextBox' (Name='textBox1'); target property is 'Text' (type 'String') TargetInvocationException:'System.Reflection.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.ApplicationException: TEST
   at WpfApplication1.Window1.set_Name2(String value) in D:\Settings\desktop\binding_exception\WpfApplication1\WpfApplication1\Window1.xaml.cs:line 31
   --- End of inner exception stack trace ---
   at System.RuntimeMethodHandle._InvokeMethodFast(Object target, Object[] arguments, SignatureStruct& sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.RuntimeMethodHandle.InvokeMethodFast(Object target, Object[] arguments, Signature sig, MethodAttributes methodAttributes, RuntimeTypeHandle typeOwner)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture, Boolean skipVisibilityChecks)
   at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, BindingFlags invokeAttr, Binder binder, Object[] index, CultureInfo culture)
   at System.Reflection.RuntimePropertyInfo.SetValue(Object obj, Object value, Object[] index)
   at MS.Internal.Data.PropertyPathWorker.SetValue(Object item, Object value)
   at MS.Internal.Data.ClrBindingWorker.UpdateValue(Object value)
   at System.Windows.Data.BindingExpression.UpdateSource(Object value)'


개인적으로 아쉬운 부분이 바로 위와 같이 데이터 바인딩 구문에서 예외를 먹어버리는 현상입니다. 아쉽긴 해도, WPF의 Validation 정책을 아시는 분들은 이런 식의 동작이 "By design"이라고 수긍이 되는 면이 있습니다.

WPF Sample Series - Handling and Reporting WPF Data Binding Validation Errors and Exceptions
; http://karlshifflett.wordpress.com/2008/04/03/wpf-sample-series-handling-and-reporting-wpf-data-binding-validation-errors-and-exceptions/


그러하니, 유효성 검사에서 자연스럽게 처리될 예외이므로 응용 프로그램 종료로 이어지는 예외 상황을 만들지 않도록 데이터 바인딩 과정에서 try/catch로 예외를 미리 처리하게 된 것입니다. 재미있는 점이 있다면, 마이크로소프트는 DataBinding 에 오류가 발생하는 것을 알 수 있도록 그나마 세심하게 배려했다는 정도!

How can I debug WPF bindings?
; http://www.beacosta.com/blog/?p=52


위의 글에 보면, 데이터 바인딩 오류에 대해 "Trace"로 오류 로그를 남기는 방법과 PresentationTraceSources.TraceLevel 을 이용한 방법을 소개해 주고 있습니다.

그래도... 이런 거에 만족할 수는 없지요? ^^ 어떻게 해서든지 저는 공용 속성의 set 접근자에서 발생하는 오류를 잡아내야 겠습니다.




단서를 찾을 수 있는 곳은 Validation을 처리하는 코드일 것 같습니다.

WPF Sample Series - Handling and Reporting WPF Data Binding Validation Errors and Exceptions 글에 보면, ExceptionValidationErrorHandler 코드를 볼 수 있는데요.

void ExceptionValidationErrorHandler(object sender, RoutedEventArgs e)
{
    System.Windows.Controls.ValidationErrorEventArgs arg = e as System.Windows.Controls.ValidationErrorEventArgs;

    ;
}


해답은 바로 위의 arg 인자에서 제공되는 Error 속성에 있습니다. 보통 ExceptionValidationErrorHandler 가 실행되는 경우는 다음과 같은 2가지 경우입니다.

  • 위에서 설명한 데로 set 접근자에서 오류가 발생한 경우, 또는 타입이 달라서 예외가 발생한 경우
  • IDataErrorInfo 를 구현한 개체가 해당 속성의 값이 유효하지 않다고 하는 경우


이 2가지를 구분하려면 arg.Error.RuleInError의 타입으로 검사하면 됩니다.

  • (arg.Error.RuleInError is ExceptionValidationRule) == true: 첫번째 경우
  • (arg.Error.RuleInError is DataErrorValidationRule) == true: 두번째 경우


이런 것을 반영해 보면 다음과 같은 식으로 코드를 만들면 될 것 같습니다.

void ExceptionValidationErrorHandler(object sender, RoutedEventArgs e)
{
    System.Windows.Controls.ValidationErrorEventArgs arg = e as System.Windows.Controls.ValidationErrorEventArgs;

    if (arg.Error.Exception != null && arg.Error.RuleInError is ExceptionValidationRule)
    {
        if (arg.Error.Exception is System.FormatException)
        {
            // 대개의 경우 발생할 수 있는 ExceptionValidationRule
        }
        else
        {
            // 그 외의 예외는 의도적이지 않은 예외
            throw arg.Error.Exception.InnerException;
        }
    }
}


이렇게 되면, 타입이 일치하지 않아 발생하는 예외는 그대로 Validation 검사로 진행하도록 하고, 그 이외의 상황에서는 throw를 해서 개발자로 하여금 set접근자에서 예외가 발생했음을 알 수 있도록 해줍니다.




그나마 예외 상황을 잡아보긴 했지만 아직 해결되지 않은 문제가 있습니다. ExceptionValidationErrorHandler 단계에서는 스택이 이미 풀린 상태이기 때문에 정확히 오류가 발생하는 곳에 코드를 위치시킬 방법이 없습니다. 할 수 없이, 예외가 발생했다는 정도만을 정확하게 인식하고 "throw arg.Error.Exception.InnerException"에서 확인할 수 있는 예외를 디버그 예외 상자에 등록하거나, 아니면 여전히 Output창의 "First-chance Exception"을 확인해서 디버그 예외 상자에 등록해 두는 식으로 접근해야 합니다.

게다가... 또 한가지 아쉬운 것은.

Validation 처리 과정으로 넘어오지 않은 예외에 대해서는 여전히 잡을 방법이 없습니다. 예를 들어, 데이터바인딩에는 "Name2"라는 속성명인데, 실제로는 그러한 속성이 없는 경우에는 ExceptionValidationErrorHandler까지 진입하지도 않습니다. 어쩔 수 없이 "How can I debug WPF bindings?" 에서 설명한 방식으로 데이터바인딩 예외를 추적하는 방법을 따라야 합니다.

관련 예제 코드는 첨부 파일에 올려놓았습니다.


출처 : http://www.sysnet.pe.kr/Default.aspx?mode=2&sub=0&detail=1&pageno=0&wid=746&rssMode=1&wtype=0

Posted by 역시인생한방
,