una try tipos sharp que existen excepción excepciones errores ejemplo como catch capturar c# .net exception-handling try-catch

tipos - try catch c# ejemplo



¿Cuándo usar los bloques try/catch? (5)

Como han dicho otros, desea utilizar el bloque try catch alrededor del código que puede generar una Excepción Y que está preparado para enfrentar.

Para sus ejemplos particulares, File.Delete puede lanzar una cantidad de excepciones, incluyendo IOException, UnauthorizedAccessException y otras. ¿Qué te gustaría que hiciera tu aplicación en esas situaciones? Si intenta eliminar el archivo pero alguien en otro lugar lo está utilizando, obtendrá una excepción IOException.

try { File.Delete(pgpdFilename + "_archive") } catch(IOException) { UtilityLogger.LogToFile("File is in use, could not overwrite."); //do something else meaningful to your application //perhaps save it under a different name or something }

También tenga en cuenta que si esto falla, entonces el archivo. Mover lo que haga fuera de su bloque if también bloqueará (de nuevo a una excepción IOException, ya que el archivo no se eliminó, todavía está allí, lo que causará que falle el movimiento) .

He leído y entiendo lo que hace un bloque Try / Catch y por qué es importante usar uno. Pero estoy atascado en saber cuándo y dónde usarlos. ¿Algún consejo? A continuación, publicaré una muestra de mi código con la esperanza de que alguien tenga tiempo para hacer algunas recomendaciones para mi ejemplo.

public AMPFileEntity(string filename) { transferFileList tfl = new transferFileList(); _AMPFlag = tfl.isAMPFile(filename); _requiresPGP = tfl.pgpRequired(filename); _filename = filename.ToUpper(); _fullSourcePathAndFilename = ConfigurationSettings.AppSettings.Get("sourcePath") + _filename; _fullDestinationPathAndFilename = ConfigurationSettings.AppSettings.Get("FTPStagePath") + _filename; _hasBeenPGPdPathAndFilename = ConfigurationSettings.AppSettings.Get("originalsWhichHaveBeenPGPdPath"); } public int processFile() { StringBuilder sb = new StringBuilder(); sb.AppendLine(" "); sb.AppendLine(" --------------------------------"); sb.AppendLine(" Filename: " + _filename); sb.AppendLine(" AMPFlag: " + _AMPFlag); sb.AppendLine(" Requires PGP: " + _requiresPGP); sb.AppendLine(" --------------------------------"); sb.AppendLine(" "); string str = sb.ToString(); UtilityLogger.LogToFile(str); if (_AMPFlag) { if (_requiresPGP == true) { encryptFile(); } else { UtilityLogger.LogToFile("This file does not require encryption. Moving file to FTPStage directory."); if (File.Exists(_fullDestinationPathAndFilename)) { UtilityLogger.LogToFile(_fullDestinationPathAndFilename + " alreadyexists. Archiving that file."); if (File.Exists(_fullDestinationPathAndFilename + "_archive")) { UtilityLogger.LogToFile(_fullDestinationPathAndFilename + "_archive already exists. Overwriting it."); File.Delete(_fullDestinationPathAndFilename + "_archive"); } File.Move(_fullDestinationPathAndFilename, _fullDestinationPathAndFilename + "_archive"); } File.Move(_fullSourcePathAndFilename, _fullDestinationPathAndFilename); } } else { UtilityLogger.LogToFile("This file is not an AMP transfer file. Skipping this file."); } return (0); } private int encryptFile() { UtilityLogger.LogToFile("This file requires encryption. Starting encryption process."); // first check for an existing PGPd file in the destination dir. if exists, archive it - otherwise this one won''t save. it doesn''t overwrite. string pgpdFilename = _fullDestinationPathAndFilename + ".PGP"; if(File.Exists(pgpdFilename)) { UtilityLogger.LogToFile(pgpdFilename + " already exists in the FTPStage directory. Archiving that file." ); if(File.Exists(pgpdFilename + "_archive")) { UtilityLogger.LogToFile(pgpdFilename + "_archive already exists. Overwriting it."); File.Delete(pgpdFilename + "_archive"); } File.Move(pgpdFilename, pgpdFilename + "_archive"); } Process pProc = new Process(); pProc.StartInfo.FileName = "pgp.exe"; string strParams = @"--encrypt " + _fullSourcePathAndFilename + " --recipient infinata --output " + _fullDestinationPathAndFilename + ".PGP"; UtilityLogger.LogToFile("Encrypting file. Params: " + strParams); pProc.StartInfo.Arguments = strParams; pProc.StartInfo.UseShellExecute = false; pProc.StartInfo.RedirectStandardOutput = true; pProc.Start(); pProc.WaitForExit(); //now that it''s been PGPd, save the orig in ''hasBeenPGPd'' dir UtilityLogger.LogToFile("PGP encryption complete. Moving original unencrypted file to " + _hasBeenPGPdPathAndFilename); if(File.Exists(_hasBeenPGPdPathAndFilename + _filename + "original_which_has_been_pgpd")) { UtilityLogger.LogToFile(_hasBeenPGPdPathAndFilename + _filename + "original_which_has_been_pgpd already exists. Overwriting it."); File.Delete(_hasBeenPGPdPathAndFilename + _filename + "original_which_has_been_pgpd"); } File.Move(_fullSourcePathAndFilename, _hasBeenPGPdPathAndFilename + _filename + "original_which_has_been_pgpd"); return (0); } }

}


La regla básica para capturar excepciones es capturar excepciones solo si tiene una manera significativa de manejarlas .

No detecte una excepción si solo va a registrar la excepción y lanzarla a la pila. No sirve ningún significado y desordena el código.

Detecta una excepción cuando esperas una falla en una parte específica de tu código, y si tienes un respaldo para ello.

Por supuesto, siempre tiene el caso de las excepciones comprobadas que requieren que use los bloques try / catch, en cuyo caso no tiene otra opción. Incluso con una excepción marcada, asegúrese de iniciar sesión correctamente y manejar de la manera más limpia posible.


Los otros muchachos han dado un buen número de buenos punteros y referencias.

Mi entrada es corta:
Cuando usarlo es una cosa, igual o más importante es cómo usarlo correctamente.

PD: "eso" es una referencia a "intentar y atrapar excepciones".


Me enseñaron a usar try / catch / finalmente para cualquier método / clase en el que pudieran ocurrir múltiples errores y que realmente pueda manejar . Transacciones de base de datos, E / S del sistema de archivos, transmisión, etc. La lógica del núcleo generalmente no requiere probar / capturar / finalmente.

La gran parte de probar / capturar / finalmente es que puede tener múltiples capturas para que pueda crear una serie de controladores de excepciones para lidiar con errores muy específicos o usar una excepción general para detectar cualquier error que no vea venir.

En su caso, está utilizando File.Exists, lo cual es bueno, pero quizás haya otro problema con el disco que puede generar otro error que File.Exists no puede manejar. Sí, es un método booleano, pero di que el archivo está bloqueado y ¿qué sucede si intentas escribir en él? Con la captura, puede planificar un escenario raro, pero sin probar / capturar / finalmente, puede estar exponiendo el código a condiciones completamente imprevistas.