【JAVA】try,catch的使用

转载自点击打开链接

异常的处理是为了解决这样的问题:

  1. 1.当出现异常时,友好提示。  
  2. 2.帮我们开发人员准确快速的记录并定位问题。 
  1. 异常处理关键字  
  2. 为了能够对异常进行处理,java里面提供了指定的关键字。  
  3. 1、throw   
  4. throw是为了抛出异常给java运行环境,让它进行处理  
  5. 2、throws   
  6. 如果在一个方法中产生了一个异常并且我们不想对其进行处理,我们就在方法上使用throws关键字,目的是为了让这个方法的调用者知道这个方法可能产生异常,这个方法的调用者可以处理这个异常也可以使用同样的方法来告诉上层的调用者。  
  7. 3、try-catch   
  8. try-catch是处理异常的代码块。  
  9. 4、finally   
  10. finally块只能跟try-catch块一块使用,由于异常中断了程序的执行,这样我们有一些资源可能被打开了但是还没来得及关闭,这样就可以使用finally块,不管会不会产生异常finally块都会被执行。  
下面看try catch的使用

1.不适用try catch,遇到异常程序就不能走下去

  1. public class TryCatch {  
  2.   
  3.     public static void main(String[] args) {  
  4.         int i=1/0;  
  5.         System.out.println(123);//此行无法执行  
  6.   
  7.     }  
  8.   
  9. }  


2.使用try catch,异常的地方可以被捕获,程序可以继续执行
  1. public static void main(String[] args) {  
  2.         try {  
  3.             int i = 1 / 0;  
  4.         } catch (Exception e) {  
  5.             e.printStackTrace();  
  6.         }  
  7.         System.out.println(123);//可以执行此行  
  8.   
  9.     } 

有关trycatch使用

06-11

BOOL CLogin::PreTranslateMessage(MSG* pMsg) rnrn // TODO: Add your specialized code here and/or call the base classrn if(pMsg->message==WM_KEYDOWN && pMsg->wParam==VK_RETURN)rn rn pMsg->wParam = 9;rn rn if(pMsg->message == WM_LBUTTONDOWN)rn rn CRect rect,rc;rn m_OK.GetWindowRect(&rect);rn m_Cancel.GetWindowRect(&rc);rn CPoint point;rn GetCursorPos(&point);rn if(rect.PtInRect(point))rn rn UpdateData(TRUE);rn if(m_Name.IsEmpty() || m_PassWord.IsEmpty())rn rn MessageBox("用户名或密码不能为空");rn return FALSE;rn rn m_Time++;rn [color=#FF0000]tryrn rn //创建连接对象实例rn m_pConnection.CreateInstance("ADODB.Connection");rn //设置连接字符串rn CString strConnect="DRIVER=Microsoft Access Driver (*.mdb);\rn uid=;pwd=;DBQ=shujuku.mdb;";rn //使用Open方法连接数据库rn m_pConnection->Open((_bstr_t)strConnect,"","",adModeUnknown);rn rn catch(_com_error e)rn rn AfxMessageBox(e.Description());rn rn CString sql;rn sql.Format("select * from tb_user where 用户名 = '%s' and 密码 = '%s'",rn m_Name,m_PassWord);rn m_pRecordset = m_pConnection->Execute((_bstr_t)sql,NULL,adCmdText);rn if(!m_pRecordset->adoEOF)rn rn CDialog::OnOK();rn [/color] elsern rn if(m_Time == 3)rn rn MessageBox("密码3次不正确");rn CDialog::OnCancel();rn rn elsern rn MessageBox("用户名或密码不正确");rn m_Name = "";rn m_PassWord = "";rn UpdateData(FALSE);rn rn rn m_pRecordset->Close();rn m_pConnection->Close(); rn rn if(rc.PtInRect(point))rn rn CDialog::OnCancel();rn rn rn return CDialog::PreTranslateMessage(pMsg);rnrnrn各位,以上是我看的一段有关制作用户登录模块的程序,其中红色字体部分看的云里雾里的,望高人指点,特别是try和catch的那两段,先谢谢了

TRY CATCH?

09-27

[code=C/C++]rnBOOL CWlApp::InitInstance()rnrn // Standard initializationrn // If you are not using these features and wish to reduce the sizern // of your final executable, you should remove from the followingrn // the specific initialization routines you do not need.rnrn#ifdef _AFXDLLrn Enable3dControls(); // Call this when using MFC in a shared DLLrn#elsern Enable3dControlsStatic(); // Call this when linking to MFC staticallyrn#endifrnrn // Change the registry key under which our settings are stored.rn // TODO: You should modify this string to be something appropriatern // such as the name of your company or organization.rn SetRegistryKey(_T("Local AppWizard-Generated Applications"));rnrn LoadStdProfileSettings(); // Load standard INI file options (including MRU)rnrn // Register the application's document templates. Document templatesrn // serve as the connection between documents, frame windows and views.rnrn CMultiDocTemplate* pDocTemplate;rn pDocTemplate = new CMultiDocTemplate(rn IDR_SCRIBTYPE,rn RUNTIME_CLASS(CWlDoc),rn RUNTIME_CLASS(CChildFrame), // custom MDI child framern RUNTIME_CLASS(CWlView));rn AddDocTemplate(pDocTemplate);rnrn // create main MDI Frame windowrn CMainFrame* pMainFrame = new CMainFrame;rn if (!pMainFrame->LoadFrame(IDR_MAINFRAME))rn return FALSE;rn m_pMainWnd = pMainFrame;rnrn // Enable drag/drop openrn m_pMainWnd->DragAcceptFiles();rnrn // Enable DDE Execute openrn EnableShellOpen();rn RegisterShellFileTypes(TRUE);rnrn // Parse command line for standard shell commands, DDE, file openrn CCommandLineInfo cmdInfo;rn ParseCommandLine(cmdInfo);rnrn // Dispatch commands specified on the command linern if (!ProcessShellCommand(cmdInfo))rn return FALSE;rnrn // The main window has been initialized, so show and update it.rn pMainFrame->ShowWindow(m_nCmdShow);rn pMainFrame->UpdateWindow();rn rn CString str="hello world!!!";rn TRYrn CFile file("hello.txt",CFile::modeCreate|CFile::modeCreate);rn file.Write(str,str.GetLength());rn file.Close();rn rn CATCH(CFileException,e)rn switch(e->m_cause)rn case CFileException::accessDenied:rn TRACE("FILE access denied");rn break;rn case CFileException::badPath:rn TRACE("bad path");rn break;rn case CFileException::diskFull:rn TRACE("disk full");rn break;rn case CFileException::fileNotFound:rn TRACE("fileNotFound");rn break;rn case CFileException::hardIO:rn TRACE("hardware erro");rn break;rn case CFileException::lockViolation:rn TRACE("attemp to lock region aready locked");rn break;rn case CFileException::sharingViolation:rn TRACE("sharingViolation-load share.exe");rn break;rn case CFileException::tooManyOpenFiles:rn TRACE("tooManyOpenFiles");rn break;rn rn rnrn// return 0;rn return TRUE;rnrnrnrn/////////////////////////////////////////////////////////////////////////////rn// CAboutDlg dialog used for App Aboutrnrnclass CAboutDlg : public CDialogrnrnpublic:rn CAboutDlg();rnrn// Dialog Datarn //AFX_DATA(CAboutDlg)rn enum IDD = IDD_ABOUTBOX ;rn //AFX_DATArnrn // ClassWizard generated virtual function overridesrn //AFX_VIRTUAL(CAboutDlg)rn protected:rn virtual void DoDataExchange(CDataExchange* pDX); // DDX/DDV supportrn //AFX_VIRTUALrnrn// Implementationrnprotected:rn //AFX_MSG(CAboutDlg)rn // No message handlersrn //AFX_MSGrn DECLARE_MESSAGE_MAP()rn;rnrnCAboutDlg::CAboutDlg() : CDialog(CAboutDlg::IDD)rnrn //AFX_DATA_INIT(CAboutDlg)rn //AFX_DATA_INITrnrnrnvoid CAboutDlg::DoDataExchange(CDataExchange* pDX)rnrn CDialog::DoDataExchange(pDX);rn //AFX_DATA_MAP(CAboutDlg)rn //AFX_DATA_MAPrnrnrnBEGIN_MESSAGE_MAP(CAboutDlg, CDialog)rn //AFX_MSG_MAP(CAboutDlg)rn // No message handlersrn //AFX_MSG_MAPrnEND_MESSAGE_MAP()rnrn// App command to run the dialogrnvoid CWlApp::OnAppAbout()rnrn CAboutDlg aboutDlg;rn aboutDlg.DoModal();rnrnrn/////////////////////////////////////////////////////////////////////////////rn// CWlApp message handlersrnrn[/code]rnrnrn在初始化实例中使用TRY CATCH后,出现如下错误,去掉TRY CATCH一切正常!WHY?rnCompiling...rnMainFrm.cpprnwl.cpprnC:\Documents and Settings\Administrator\桌面\wl\wl.cpp(153) : error C2599: 'CAboutDlg::CAboutDlg' : local class member functions must be defined within the classrn C:\Documents and Settings\Administrator\桌面\wl\wl.cpp(153) : see declaration of 'CAboutDlg::CAboutDlg'rnC:\Documents and Settings\Administrator\桌面\wl\wl.cpp(163) : error C2599: 'DoDataExchange' : local class member functions must be defined within the classrn C:\Documents and Settings\Administrator\桌面\wl\wl.cpp(163) : see declaration of 'DoDataExchange'rnC:\Documents and Settings\Administrator\桌面\wl\wl.cpp(171) : error C2246: '_messageEntries' : illegal static data member in locally defined classrnC:\Documents and Settings\Administrator\桌面\wl\wl.cpp(171) : error C2246: 'messageMap' : illegal static data member in locally defined classrnC:\Documents and Settings\Administrator\桌面\wl\wl.cpp(171) : error C2599: '_GetBaseMessageMap' : local class member functions must be defined within the classrn C:\Documents and Settings\Administrator\桌面\wl\wl.cpp(171) : see declaration of '_GetBaseMessageMap'rnC:\Documents and Settings\Administrator\桌面\wl\wl.cpp(171) : error C2599: 'GetMessageMap' : local class member functions must be defined within the classrn C:\Documents and Settings\Administrator\桌面\wl\wl.cpp(171) : see declaration of 'GetMessageMap'rnC:\Documents and Settings\Administrator\桌面\wl\wl.cpp(174) : error C2143: syntax error : missing ';' before ':'rnC:\Documents and Settings\Administrator\桌面\wl\wl.cpp(175) : error C2143: syntax error : missing ';' before ''rnC:\Documents and Settings\Administrator\桌面\wl\wl.cpp(181) : error C2601: 'DoDataExchange' : local function definitions are illegalrnC:\Documents and Settings\Administrator\桌面\wl\wl.cpp(187) : error C2601: '_GetBaseMessageMap' : local function definitions are illegalrnC:\Documents and Settings\Administrator\桌面\wl\wl.cpp(187) : error C2601: 'GetMessageMap' : local function definitions are illegalrnC:\Documents and Settings\Administrator\桌面\wl\wl.cpp(187) : error C2655: 'messageMap' : definition or redeclaration illegal in current scopern C:\Documents and Settings\Administrator\桌面\wl\wl.cpp(171) : see declaration of 'messageMap'rnC:\Documents and Settings\Administrator\桌面\wl\wl.cpp(187) : error C2655: '_messageEntries' : definition or redeclaration illegal in current scopern C:\Documents and Settings\Administrator\桌面\wl\wl.cpp(171) : see declaration of '_messageEntries'rnC:\Documents and Settings\Administrator\桌面\wl\wl.cpp(195) : error C2601: 'OnAppAbout' : local function definitions are illegalrnC:\Documents and Settings\Administrator\桌面\wl\wl.cpp(203) : fatal error C1004: unexpected end of file foundrnGenerating Code...rnError executing cl.exe.rnrnwl.exe - 15 error(s), 0 warning(s)rn

没有更多推荐了,返回首页

私密
私密原因:
请选择设置私密原因
  • 广告
  • 抄袭
  • 版权
  • 政治
  • 色情
  • 无意义
  • 其他
其他原因:
120
出错啦
系统繁忙,请稍后再试