Professional Documents
Culture Documents
Try Catch Roundup
Try Catch Roundup
Ef vitað er að villan getur komið: brugðist við því í kóða
Ef við vitum ekki hvort villa kemur upp eða við höfum ekki stjórn á því: nota try‐catch
Þegar við fáum Exepction þá er talað um að villu sé kastað (thrown)
Í C# er villumeðhöndlum (Exception) á ábyrgð klasans System.Exception
Til eru forskilgreindar villutegundir.
Gott er í náinni framtíð að koma sér upp þekkingu á hvaða exception getur komið fyrir hvar.
Dæmi: Ef við opnum skrá þá geta eftirfarandi Exception‐ir komið upp:
SecurityException
ArgumentException
ArgumentNullException
PathTooLongException
DirectoryNotFoundException
UnauthorizedAccessException
FileNotFoundException
NotSupportedException
Svona lítur try ‐ catch blokk út (til dæmis):
using System;
using System.IO;
class tryCatchDemo
{
static void Main(string[] args)
{
try
{
File.OpenRead("NonExistentFile");
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString()); // Allar villur gripnar hér
}
}
}
Svo má líka gera svona:
using System;
using System.IO;
class tryCatchDemo
{
static void Main(string[] args)
{
try
{
File.OpenRead("NonExistentFile");
}
catch(FileNotFoundException fnfex)
{
Console.WriteLine(fnfex.ToString());
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
Almenn villa (Exception) er höndluð síðast. Sértækar villur á undan
Svo er náttúrulega try – chatch – finally :
Í þessu dæmi fær finally það hlutverk að loka skránum ef þær hafa opnast.
using System;
using System.IO;
class FinallyDemo
{
static void Main(string[] args)
{
FileStream outStream = null;
FileStream inStream = null;
try
{
outStream = File.OpenWrite("DestinationFile.txt");
inStream = File.OpenRead("BogusInputFile.txt");
}
catch(Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
if (outStream != null)
{
outStream.Close();
Console.WriteLine("outStream closed.");
}
if (inStream != null)
{
inStream.Close();
Console.WriteLine("inStream closed.");
}
}
}
}