본문 바로가기
MFC

[MFC] Exception handle, try catch, event viewer

by Jcoder 2022. 11. 4.

	try
	{
		int i;
		i++;
		AfxThrowUserException();
	}
	catch (CException* ce)
	{
		CString strExceptionMessage;
		TCHAR szMsg[1024];
		memset(szMsg, 0x00, sizeof(szMsg));

		if (ce->GetErrorMessage(szMsg, 1024))
		{
			CString strErrorMessage = szMsg;
			strExceptionMessage.Format(
				//_T("Url - %s\n")
				_T("Error Code - %d\n")
				_T("Error Message - %s\n")
				_T("Error Line - %d\n")
				_T("test")
				, GetLastError()
				, strErrorMessage
				, __LINE__);

			AfxMessageBox(strExceptionMessage, MB_ICONERROR | MB_OK);

			System::String^ sApplication = gcnew System::String(System::Reflection::Assembly::GetExecutingAssembly()->GetName()->Name);
			System::String^ sExceptionMessage = gcnew System::String(strExceptionMessage);

			if (!System::Diagnostics::EventLog::SourceExists(sApplication))
				System::Diagnostics::EventLog::CreateEventSource(sApplication, "Application");

			System::Diagnostics::EventLog::WriteEntry(sApplication, sExceptionMessage, System::Diagnostics::EventLogEntryType::Error);
		}
	}