728x90
반응형

02. 제어문


선택문

 

- if ~ else

4-6 예제)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _4_6
{
    class Program
    {
        static void Main(string[] args)
        {
            int nNum = 10;
            if (true) // nNum이 들어가면 에러가 난다.  
                Console.WriteLine("Hello World!");
            else
                Console.WriteLine("C# Programming");
           
        }
    }
}

 

- switch, case

  1. 정수, 문자상사, 문자열

  2. 모든 case와 default에는 break가 반드시 있어야 한다.

 

4-7 예제)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _4_7
{
    class Program
    {
        static void Main(string[] args)
        {
            int nNum = 1;
            switch (nNum)
            {
                case 1:  // 진행하지 않는다.
                    Console.WriteLine("1 입니다."); // 1
                    break; // break를 사용하지않으면 case에서 에러(빨간줄)가뜬다
                case 2:
                    Console.WriteLine("2 입니다.");
                    break;
            }
        }
    }
}

4-8 예제)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _4_8
{
    class Program
    {
        static void Main(string[] args)
        {
            string str = "yes";
            switch (str)
            {
                case "no":
                    Console.WriteLine("no 입니다.");
                    break;
                case "yes":
                    Console.WriteLine("yes 입니다.");
                    break;
            }
        }
    }
}

4-9 예제)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _4_9
{
    class Program
    {
        static void Main(string[] args)
        {
            char value = 'a'; // 유니코드 2byte (1byte x)
            switch (value)
            {
                case 'a':
                    Console.WriteLine("a 입니다.");
                    break;
                case 'b':
                    Console.WriteLine("b 입니다.");
                    break;
            }
        }
    }
}

 

반복문

  • for                       for(;;) -> 무한반복

  • while, do~while      while(true) -> 무한반복

  • foreach                 처음부터 까지 순차적인 값을 반복하여 읽는 역할 -> 읽기 전용

foreach(데이터형 변수 in 배열명(컬렉션명))
{
}

 

4-11 예제)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _4_11
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] Array1 = { 1, 2, 3, 4 };
            
            foreach (int nValue in Array1) // nValue는 읽기 전용(값을 저장할 수 없다)
            {
                Console.WriteLine(nValue); // 1 2 3 4                
            }
        }
    }
}

4-12 예제)

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _4_12
{
    class Program
    {
        static void Main(string[] args)
        {
            ArrayList List = new ArrayList(); 
            List.Add(1); // 값을 추가 할때 Add라는 메서드 사용
            List.Add(2); 
            List.Add(3);
            // list에 1,2,3이 차례대로 들어감

            foreach (int m in List) // list에 1,2,3이 m으로 차례대로 읽혀짐
            {
                Console.WriteLine(m); // 1 2 3 출력
            }
        }
    }
}

 

 

03. 점프문


  • goto, continue, return, break

 

 

 

04. 예외 처리문


  • 예외란?  런타임 시에 발생할 수 있는 오류

  • 예외 처리방법 : if ~ else         try ~ catch 문 사용

 

try ~ catch

try
{
    // 예외가 발생할 수 있는 코드
}catch(예외처리객체 e) <- 에러가 발생한 원인

{
    // 예외 처리
}
  • System.Excpetion 파생 객체만 사용

- System.Exception 파생객체

    OverFlowException,

    FormatException,

    DivideByZeroException,

    FileNotFoundException

 

- IndexOutOfRangeException

 

4-13 예제)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _4_13
{
    class Program
    {   
        static void Main(string[] args)
        {
            int[] array = { 1, 2, 3 };
            try
            {
                array[3] = 10; //예외 발생
            }
            catch (IndexOutOfRangeException e)
            {
                //Console.WriteLine("배일 인덱스 에러 발생");
                //Console.WriteLine(e.ToString()); // 에러 원인 설명
                array[2] = 10;
            }

            for (int i = 0; i < array.Length; i++)
                Console.Write("{0} ", array[i]);            
        }
    }
}

 

  • try 문 안에서 초기화한 변수를 try문 밖에서 사용할 수 없다.

4-14 예제)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _4_14
{
    class Program
    {
        static void Main(string[] args)
        {
            int m = 0;
            try
            {
                m = 12;
                Console.WriteLine("try문 출력 :{0}", m);
            }
            catch
            {
                Console.WriteLine("예외 발생");
            }

            Console.WriteLine("try 문 밖에서 변수 출력 {0}", m); // <-- 에러 표시
        }
    }
}

 

 

try - finally

  • finally 예외 발생과 상관없이 항상 실행되는 구문

  • 예외적인 상황이 발생했을 때 finally 처리

4-15예제)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _4_15
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = { 1, 2, 3 };
            try
            {
                Console.WriteLine("try 문에서 예외 발생시킵니다");
                array[3] = 10;
            }
            // 실행(O)
            finally
            {
                Console.WriteLine("finally 구문입니다.");
            }
			// 실행(X)
            foreach(var m in array)
                Console.Write("{0} ", m);            
        }
    }
}

 

  • 예외상황이 발생하지 않았을 때 finally 처리

4-16 예제)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _4_16
{
    class Program
    {
        static void Main(string[] args)
        {
            int i = 0;
            try
            {
                i = 12;
            }
            // 여기서 error없이 finally 구문은 동일하게 실행한다.
            // catch문은 예외가 발생되야 실행된다.
            finally
            {
                i = 100;
                Console.WriteLine("finally 문 i 값 : {0}", i); // 100 출력
            }

            i = 200;
            Console.WriteLine("try finally문 밖에서 실행 i 값 :{0}", i); // 200 출력
        }
    }
}

 

다중 예외 처리

  • 형식
try
{
    ......
}catch (OverFlowException e)  // 예외가 발생되야 실행

{   ...... 
}catch (FormatException e)

{   ......
}catch (DivideByZeroException e)

{   ......
}

 

 

throw

  • throw (던지다) : 예외 상황을 임의로 발생시키는 역할

  • System.Exception 파생된 객체만 사용

  • try문과 그 외에서 사용가능

 

4-18 예제)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace _4_18
{
    class Program
    {
        static int GetNumber(int index) // index = 3
        {
            int[] nums = { 300, 600, 900 };
            if (index >= nums.Length) // nums.Length : 배열의 개수 = 3
            {
                throw new IndexOutOfRangeException(); // 에러를 던져라
            }
            return nums[index];
        }

        static void Main(string[] args)
        {
            int result = GetNumber(3);
        }
    }
}

 

 

 

정리


  • 대부분의 연산자는 C, C++언어와 같다.

  • C#에서 새롭게 등장한 연산자  is연산자, as연산자, null병합연산자(??)

  • for, while, do ~ while, foreach

  • 예외처리문 : try ~ catch ~ finally, throw new

728x90
반응형

+ Recent posts