[英]how to use try catch blocks in a value returning method?
我正在注冊表中檢查上傳的圖像,我需要在其中使用 try catch 塊。 這是我的代碼:
public bool CheckFileType(string FileName)
{
string Ext = Path.GetExtension(FileName);
switch (Ext.ToLower())
{
case ".gif":
return true;
break;
case ".JPEG":
return true;
break;
case ".jpg":
return true;
break;
case ".png":
return true;
break;
case ".bmp":
return true;
break;
default:
return false;
break;
}
}
請在這里建議我如何使用 try catch 塊。
提前致謝。
這樣做會更好,
public bool CheckFileType(string FileName)
{
bool result = false ;
try
{
string Ext = Path.GetExtension(FileName);
switch (Ext.ToLower())
{
case ".gif":
case ".JPEG":
case ".jpg":
case ".png":
case ".bmp":
result = true;
break;
}
}catch(Exception e)
{
// Log exception
}
return result;
}
有很多方法可以在返回值的方法中使用異常:
將您的退貨聲明放在 try-catch 之外例如:
T returnValue = default(T);
try
{
// My code
}
catch
{
// Exception handling code
}
return returnValue;
在你的 catch 里放一個 return 語句
try
{
// My code
}
catch
{
// Handle exception
return default(T);
}
拋出異常
您不必返回值,該方法只需結束(例如,到達返回語句或拋出語句)。 根據異常,返回值並不總是有效。
您應該仔細考慮何時以及如何捕獲和處理異常:
在你的情況下:
string Ext = Path.GetExtension(FileName);
,根據文檔,如果FileName
包含它可能會失敗。 (請注意,即使FileName
為空, GetExtension
也不返回 null)。所以我可能會處理這樣的異常:
public bool CheckFileType(string FileName)
{
string Ext;
try
{
Ext = Path.GetExtension(FileName);
}
catch (ArgumentException ex)
{
return false;
}
// Switch statement
}
請注意,我們只捕獲我們預期的異常( ArgumentException
),並且我們只將try
語句放置在我們希望拋出異常的語句周圍。
事實上,盡可能避免拋出和捕獲異常是一個好主意——它們不僅會導致性能損失(如果在循環內調用此方法可能會導致嚴重問題),而且您可能會無意中捕獲並處理您遇到的異常沒想到,掩蓋了更嚴重的問題。
在這種情況下,我們可以通過檢查FileName
是否包含任何無效字符來完全避免拋出異常:
public bool CheckFileType(string FileName)
{
if (FileName == null)
{
return false;
}
if (FileName.IndexOfAny(System.IO.Path.GetInvalidPathChars()) >= 0)
{
return false;
}
// Your original method goes here
}
由於您實際上並未測試文件類型(僅文件名的擴展名),因此我首先要重命名該方法。 您可以制作一個擴展方法來處理它:
public static bool HasImageExtension(this string fileName)
{
try
{
if (fileName == null) return false;
string[] validExtensions = new string[] { ".gif", ".jpg", ".jpeg", ".png", ".bmp" };
string extension = Path.GetExtension(fileName);
return validExtensions.Contains(extension);
}
// catch the specific exception thrown if there are
// invalid characters in the path
catch (ArgumentException ex)
{
// do whatever you need to do to handle
// the fact there are invalid chars
throw;
}
}
然后您可以調用它,如下所示:
string fileName = "testFileName.jpg";
bool hasImageExtension = fileName.HasImageExtension();
這應該有效:
public bool CheckFileType(string FileName)
{
try
{
string Ext = Path.GetExtension(FileName).ToLower();
string[] okExt = ".gif|.jpg|.jpeg|.png|.bmp".Split('|');
foreach(var item in okExt)
{
if(Ext == item)
return true;
}
return false;
}
catch(Exception ex)
{
throw;
}
}
請記住:永遠不要捕獲您不會處理的異常。 (或至少重新扔掉它們)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.