Machineboy空
C# Exceptions 예외 처리하기 : Try-Catch 문 본문
프로그램이 비정상적인 상황을 만났을 때 이를 처리하는 예외 처리
- 예외(Exception) : 프로그래머가 생각한 시나리오에서 벗어나는 사건
- 예외 처리(Exception Handling) : 예외가 프로그램의 오류나 다운으로 이어지지 않도록 적절하게 처리하는 것
예외를 처리하지 못해 죽는 프로그램은 아무리 기능이 많아도 신뢰할 수 없다.
System.Exception 클래스와 throw
- all exeptions have System.Exception class as their base type
- contains Message, reason for the exception being thrown
모든 예외는 System.Exception 클래스를 상속하고, 사람이 읽을 수 있는 형태의 예외 원인 메시지를 던진다.
예) Out of Index
- new exception object need to be created and thrown, using the throw keyword
throw 키워드를 통해 새로운 예외 객체가 생성해서 던진다.
using System;
static int Square(int number)
{
if (number >= 46341)
{
// 46341보다 크면 예외 객체를 생성해서 던진다.
throw new ArgumentException($"Argument {number} cannot be higher than 46340 as its' square doesn't fit into int type.");
}
return number * number;
}
Try - Catch 문
예외가 던져진 이후의 상황
- find piece of code that is responsible for handling of that exception
예외가 발생하면 예외를 처리하는 코드를 찾는다.
- no appropriate handler is found, stop the execution of the program
예외 처리할 코드가 없으면 프로그램 실행을 멈춘다.
예외가 발생한 후 처리를 위한 try-catch문
- Try : contain and guard code that may result in the exception getting thrown
- 예외가 발생할 수 있는 코드를 담는다.
- Catch : contain code that handles the behavior after the error has occured
- 예외가 발생한 이후에 프로그램의 동작을 처리하느 코드를 담아야 한다.
try
{
if (number == 42)
{
throw new ArgumentException("The number cannot be equal to 42.", "number");
}
if (number < 0)
{
throw new ArgumentOutOfRangeException("number", "The number cannot be negative.");
}
// Process number ...
}
// 여러 개의 catch가 나열된다면 첫번째로 일치하는 catch절이 실행된다.
catch (ArgumentOutOfRangeException e)
{
Console.WriteLine($"Number is out of range: {e.Message}.");
}
catch (ArgumentException)
{
Console.WriteLine("Invalid number.");
}
예제
https://exercism.org/tracks/csharp/exercises/calculator-conundrum/edit
Exercism
Learn, practice and get world-class mentoring in over 50 languages. 100% free.
exercism.org
using System;
public static class SimpleCalculator
{
public static string Calculate(int operand1, int operand2, string? operation)
{
int cal = 0;
string answer = "";
// Division by zero check
if (operand2 == 0 && operation == "/")
{
return ("Division by zero is not allowed.");
}
// Switch for operation
switch (operation)
{
case "+":
cal = operand1 + operand2;
break;
case "*":
cal = operand1 * operand2;
break;
case "/":
cal = operand1 / operand2;
break;
case "-":
cal = operand1 - operand2;
break;
case "":
throw new ArgumentException();
case null:
throw new ArgumentNullException();
default:
throw new ArgumentOutOfRangeException();
}
answer = $"{operand1} {operation} {operand2} = {cal}";
return answer; // 위치를 여기로 수정
}
}
using System;
public static class SimpleCalculator
{
public static string Calculate(int o1, int o2, string operation) =>
operation switch
{
"*" => $"{o1} * {o2} = {o1 * o2}",
"+" => $"{o1} + {o2} = {o1 + o2}",
"/" => o2 != 0 ? $"{o1} / {o2} = {o1 / o2}" : "Division by zero is not allowed.",
"" => throw new ArgumentException(),
null => throw new ArgumentNullException(),
_ => throw new ArgumentOutOfRangeException(),
};
}
'언어 > C#' 카테고리의 다른 글
C# - Overflow, Underflow, 오버플로, 언더플로, StackOverflow, checked (0) | 2025.02.25 |
---|---|
C# Property 프로퍼티 get, set (0) | 2025.02.20 |
C# Type-testing operator : is, as, typeof 연산자 (0) | 2025.02.19 |
Excercism - Yacht : LINQ 연습 (0) | 2025.02.18 |
C# Attribute, Flag Enum (0) | 2025.02.13 |