2014-01-14 2 views
0

저는 초급 프로그래머입니다. 나는 고등학교에서 수업 중 하나로서 프로그래밍 강좌를 수강해야하므로, 많이 이해하지 못하게하기 위해 최선을 다하고 있습니다. 그 말로는 제발 쉬워 져요.내 코드에서 Try, Catch 및 Finally를 사용하는 방법을 알아야합니까?

프로젝트의 경우 이전 할당을 위해 만든 두 개의 프로그램, 산술 시퀀스를 결정하는 프로그램 및 큐브 또는 구의 볼륨을 계산하기위한 프로그램으로 돌아 가야합니다.

첫 번째 지침은 모든 변수를 정의하도록 사용자에게 묻도록 프로그램을 작성하는 것입니다. 예를 들어, 프로그램은 사용자에게 한면의 길이 또는 Cube and Sphere 프로그램의 반경 값을 입력하도록 요청합니다.

나는 프로그램을 작성할 때 이미 이것을했다고 믿지만 두 번째 방향 설정에 어려움을 겪고 있습니다. "키워드를 시도하고 잡아서 마지막으로 포함 시키며, 제대로 작동하게하십시오. 사용자가 불가능한 계산을 정의하면 표시된 오류 메시지가 있어야하며 그렇지 않은 경우 단순히 대답을 표시하는 경우에도 오류가 없음을 나타내는 조치가 있어야합니다. ").

나는이 코드를 내 코드에 넣는 법을 정말로 모른다. 누군가가 내 코드에서 설명하거나 설명해 줄 수 있다면 정말 고맙겠습니다. 여기에 내 코드 : 큐브의

볼륨 또는 구체

Sub Main() 
    Dim Type As String 
    Dim Size As String 
    Dim Length_Radius As Double 
    Dim Output As Double 

    Dim Value As Double 
    Console.WriteLine("Would you like to calculate the volume of a (C)ube or a (S)phere? *press either C or S then enter to continue*") 
    Type = Console.ReadLine 
    Type = Convert.ToString(Type) 
    Value = Asc(Type) 
    If (Value = 67) Or (Value = 99) Then 
     Console.WriteLine("The equation is x^3 where x is the length of a side. What would you like the value of x to be?") 
     Size = Console.ReadLine 
     Length_Radius = Convert.ToDouble(Size) 
     Output = (Length_Radius * Length_Radius * Length_Radius) 
     Console.WriteLine("The value of the volume of the Cube is: " & Output & ".") 
    ElseIf (Value = 83) Or (Value = 115) Then 
     Console.WriteLine("The equation is 4/3*pi*r^3 where r is the radius. What would you like the value of the radius to be?") 
     Size = Console.ReadLine 
     Length_Radius = Convert.ToDouble(Size) 
     Output = ((4/3) * 3.14 * (Length_Radius * Length_Radius * Length_Radius)) 
     Console.WriteLine("The value of the volume of a sphere is: " & Output & ".") 
    ElseIf (Value <> 83) Or (Value <> 115) Or (Value <> 67) Or (Value <> 99) Then 
     Console.WriteLine("You have inputted an incorrect value.") 

    End If 

    Console.ReadLine() 



End Sub 

산술 순서

Sub Main() 
    Dim Letters As String 
    Dim a_n, d, a_one As Double 
    Dim Output As Double 
    Console.WriteLine("This program will perform the arithmetic sequence (a(n) = a(1) + d(a(n) - 1)") 
    Console.WriteLine("What would you like the value of 'a(n)' to be? *The total number of times the sequence will repeat.*") 
    Letters = Console.ReadLine 
    a_n = Convert.ToDouble(Letters) 
    Console.WriteLine("What would you like the value of 'a(1)' to be? *The starting value.*") 
    Letters = Console.ReadLine 
    a_one = Convert.ToDouble(Letters) 
    Console.WriteLine("What would you like the value of 'd' to be? *The number that the equation is multiplied by*") 
    Letters = Console.ReadLine 
    d = Convert.ToDouble(Letters) 
    Output = (a_one + d * (a_n - 1)) 
    Console.WriteLine("The value of the arithmetic sequence is: " & Output & ".") 
    Console.ReadLine() 
End Sub 
+0

마침내 try, catch에 대한 설명서를 읽었습니까? – JohnFx

+0

문서로 당신이 실제로 Try, Catch, Finally가 무엇인지 배웠다면, 나는 주어진 수업에서 그들에 대해 조금 배웠다. 그러나 나는 프로그래밍을 이해할 수없는 것 같다. – user3192348

+0

설명서에서 몇 가지 예제를 시도해 보셨습니까? – JohnFx

답변

3

컴퓨터 작업을 수행 할 때 문제가 발생할 수 있습니다. 예를 들어, 누군가 x의 입방체를 계산하라는 요청을하지만 x를 "abc"로 입력하면 컴퓨터는 그렇게 할 수 없습니다. 올바른 프로그램은 계산을 수행하기 전에 데이터의 유효성을 검사하고 다른 가능한 작업 중에서 사용자에게 친숙한 메시지를 경고하여 오류를 부드럽게 처리하려고합니다. 코드에서 다음과 같이 작성하십시오.

 Size = Console.ReadLine 
     Length_Radius = Convert.ToDouble(Size) 

이 코드는 숫자가 아닌 값을 시도하면 오류가 발생할 수 있습니다. 이것을 작성하는 더 좋은 방법은 TryParse라는 메서드를 사용하는 것입니다.하지만 질문을 위해 Try/Catch를 사용합니다. Try/Catch를 사용하면 프로그램이 을 시도하여을 실행하여 하나 이상의 명령을 수행 할 수 있으며 오류가 발생하는 경우 프로그래머가 오류를 처리 할 수있는 catch 부분으로 제어 흐름이 이동합니다. x는 ABC 때

Dim Type As String 
      Dim Size As String 
      Dim Length_Radius As Double 
      Dim Output As Double 

      Dim Value As Double 
      Console.WriteLine("Would you like to calculate the volume of a (C)ube or a (S)phere? *press either C or S then enter to continue*") 
      Type = Console.ReadLine 
      Type = Convert.ToString(Type) 
      Value = Asc(Type) 

      Try 


      If (Value = 67) Or (Value = 99) Then 
       Console.WriteLine("The equation is x^3 where x is the length of a side. What would you like the value of x to be?") 
       Size = Console.ReadLine 
       Length_Radius = Convert.ToDouble(Size) 
       Output = (Length_Radius * Length_Radius * Length_Radius) 
       Console.WriteLine("The value of the volume of the Cube is: " & Output & ".") 
      ElseIf (Value = 83) Or (Value = 115) Then 
       Console.WriteLine("The equation is 4/3*pi*r^3 where r is the radius. What would you like the value of the radius to be?") 
       Size = Console.ReadLine 
       Length_Radius = Convert.ToDouble(Size) 
       Output = ((4/3) * 3.14 * (Length_Radius * Length_Radius * Length_Radius)) 
       Console.WriteLine("The value of the volume of a sphere is: " & Output & ".") 
      ElseIf (Value <> 83) Or (Value <> 115) Or (Value <> 67) Or (Value <> 99) Then 
       Console.WriteLine("You have inputted an incorrect value.") 

      End If 


      Catch ex As Exception 
       'VB.NET will capture the error text in a property called ex.Message. 
       'Let's show this message to the user as follows: 
       Console.WriteLine(" A problem occurred:" + Environment.NewLine + ex.Message) 

      Finally 
       'Logic will come here eventually after calculation is attempted 
       Console.WriteLine("I am done with calculations") 

      End Try 


      Console.WriteLine("Press enter to exit") 
      Console.ReadLine() 

위의 코드를 사용해보십시오 : 코드에이 개념을 적용

,이 캐치 /보십시오 사용하는 것이 한 가지 방법입니다. 디버깅 중에 프로그램 흐름을 볼 수 있도록하는 것이 가장 좋습니다. 당신은 당신의 프로그램에서 1 개의 큰 try/catch를 가져서는 안됩니다. 대신 일반적으로 문제를 예상하는 위치와 코드가 손상을 방지하거나 사용자에게 유용한 피드백을 제공 할 수있는 위치에 여러 개의 블록을 배치합니다.

다음은이 주제에 대한 또 다른 예입니다. 당신이 오히려 '경우'사용자가이 시도/캐치를 필요로하지 않는 X 용 음수 값을 입력 할 수있는 경우를 처리해야 MSDN-TryCatch1 MSDN-TryCatch2

참고.