Posts

Showing posts with the label Exception

In Java, Throw IllegalArgumentException In Loan Class

Image
Download

In Java, Basic Calculator Handling Invalid Numbers Without Exception Mechanism

Image
public class Exercise12_82{ private static int parseOrQuit(String str){ if(!str.matches("^\\d+$")){ System.out.println("Wrong input: " + str); System.exit(1); } return new Integer(str); } public static void main(String[]args){ if(3 > args.length){ System.out.println("Error: Too few arguments!"); return; } int n1 = parseOrQuit(args[0]); int n2 = parseOrQuit(args[2]); int n3 = 0; switch(args[1].charAt(0)){ case '+': n3 = n1 + n2; break; case '-': n3 = n1 - n2; break; case 'x': n3 = n1 * n2; break; case '/': n3 = n1 / n2; break; default: System.out.println("Error: Invalid operator!"); return; } System.out.printf("%d %s %d = %d%n", n1, args[1], n2, n3); } } Do...

In C#, Find Square Root Of Positive Number With Exception Handling

Image
using System; namespace cs1 { class FindSquareRoot { static void Main(string[] args) { double num, sqrt; Console.Write("Find square root of: "); string input = Console.ReadLine(); try{ num = double.Parse(input); if(0 > num) throw new ApplicationException("Number can't be negative."); sqrt = Math.Sqrt(num); Console.WriteLine("Square root is {0}", sqrt); } catch (FormatException e){ Console.WriteLine("The input should be a number."); sqrt = 0; } catch (ApplicationException e){ Console.WriteLine(e.Message); sqrt = 0; } } } } Download