Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
22 views

Abstract Class, Method, Interface and Exception (1)

Uploaded by

Dinesh R Balaji
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
22 views

Abstract Class, Method, Interface and Exception (1)

Uploaded by

Dinesh R Balaji
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 40

ABSTRACT CLASS,

METHOD, INTERFACE AND


EXCEPTION HANDLING
 Abstract method: A method without method body is called
abstract method. i.e it consist of only declaration.

 Syntax:
 Access_specifier abstract return type name(parameter list)

 Note:
 1) To implement abstract method we use abstract class
 2) Instance of abstract can’t be created.
 3) The definition of abstract method is implemented in child
class.

 Abstract Class: Its used to implement abstract method


since it cant be implemented in regular class.
 Syntax:
 Abstract class class_name

 namespace abstractmethod
 {
 class Class1 : Program
 {
 public override void div(int a, int b)
 {
 int c;
 c=a/b;
 Console.WriteLine("Division =" + c);
 }
 public override void mul(int a, int b)
 {
 int c;
 c=a*b;
 Console.WriteLine("Mul=" +c);
 }

 static void Main(string[] args)
 {
 Class1 c1 = new Class1();
 c1.add(5,10);
 c1.sub(2,5);
 c1.mul(2,3);
 c1.div(2,2);
 Console.ReadLine();

 }
 }
 }
 namespace abstractmethod
 {
 abstract class Program // parent class or base class
 {
 public void add(int a, int b)
 {
 int c;
 c = a + b;
 Console.WriteLine("sum=" +c);
 }
 public void sub(int a, int b)
 {
 int c;
 c = a - b;
 Console.WriteLine("sub=" + c);
 }
 public abstract void div(int a, int b);
 public abstract void mul(int a, int b);
 }
 }
 Interface: It’s a user defined data type, it contain
only abstract method.
 Access modifier interface name

{

 Abstract method
}

 Note:
 1) Default access modifier is public.

 2) Default member of a interface is public.

 3) By default all the method defined in the interface

is abstract.
 4) We cant declare any variable inside the interface

 5) it support multiple inheritance.


 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;

 namespace @interface
 {
 interface itest1 //base
 {
 void add(int a, int b);
 }
 interface itest2 // base
 {
 void sub(int a, int b);
 void add(int a, int b);
 }
 class Program: itest2, itest1 // child
 {
 public void add(int a, int b)
 {
 int c;
 c = a + b;
 Console.WriteLine("Sum=" + c);
 }
 public void sub(int a, int b)
 {
 int c;
 c = a - b;
 Console.WriteLine("Sum=" + c);
 }
 static void Main(string[] args)
 {
 Program p = new Program();
 p.add(10, 23);
 p.sub(25, 20);
 Console.ReadLine();
 }
 }
 }
EXCEPTION HANDLING:
 In a class, when a run time error occurs
exception is responsible..
 Abnormal termination stops so that

statements are not related to the error are


executed by using exception handling.
 We can display user friendly error message.

 Error detecting will be very easy.


 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;

 namespace exceptionhandling
 {
 class Program
 {
 static void Main(string[] args)
 {
 int a, b, c;
 Console.WriteLine("Enter the value of a and
b");
 try
 {
 a = Convert.ToInt32(Console.ReadLine());
 b = Convert.ToInt32(Console.ReadLine());
 c = a / b;
 Console.WriteLine("division=" + c);
 Console.ReadLine();
 }
 /*catch (DivideByZeroException ex1)
 {
 Console.WriteLine("division is not possible");
 Console.ReadLine();
 }*/
 /*catch (OverflowException ex2)
 {
 Console.WriteLine(ex2.Message);
 Console.ReadLine();
 }*/
 catch (Exception ex)
 {
 Console.WriteLine(ex.Message);
 Console.ReadLine();
 }
 finally
 {
 Console.WriteLine("Thank you for using VS
software");
 }
 }
 }
 }
 Exceptions provide a way to transfer control
from one part of a program to another.
 C# exception handling is built upon four

keywords: try, catch, finally, and throw.


 try − A try block identifies a block of code for
which particular exceptions is activated. It is
followed by one or more catch blocks.
 catch − A program catches an exception with an
exception handler at the place in a program where
you want to handle the problem. The catch
keyword indicates the catching of an exception.
 finally − The finally block is used to execute a
given set of statements, whether an exception is
thrown or not thrown. For example, if you open a
file, it must be closed whether an exception is
raised or not.
 throw − A program throws an exception when a
problem shows up. This is done using a throw
keyword.
 try {
 // statements causing exception
 } catch( ExceptionName e1 ) {
 // error handling code
 } catch( ExceptionName e2 ) {
 // error handling code
 } catch( ExceptionName eN ) {
 // error handling code
 } finally {
 // statements to be executed
 }
EXCEPTION CLASSES IN C#
 The exception classes in C# are mainly
directly or indirectly derived from
the System.Exception class.
 Exception class are the
 System.ApplicationExceptionand
 System.SystemException classes.
 The System.SystemException class is the
base class for all predefined system
exception.
 The SystemException is a predefined
exception class in C#. It is used to handle
system related exceptions. It works as base
class for system exception namespace. It has
various child classes like:
ValidationException, ArgumentException,
ArithmeticException, DataException,
StackOverflowException etc.
APPLICATIONEXCEPTION CLASS
 An Application-level exception occurs when a
recoverable error is encountered, for
example, the wrong type of input data,
arithmetic exceptions etc.

 These are user-defined exceptions thrown by


the application and mostly the program can
resume back to its ordinary course of
instructions after solving this type exception.
 using System;
 class ExceptionTestClass {
 public static void Main() {
 int x = 0;
 try {
 int y = 100 / x;
 }
 catch (ArithmeticException e)
 {
 Console.WriteLine($"ArithmeticException Handler: {e}");
 }
 catch (Exception e)
 {
 Console.WriteLine($"Generic Exception Handler: {e}");
 }
 }
 }
 /*
 This code example produces the following results:
 ArithmeticException Handler: System.DivideByZeroException:
Attempted to divide by zero. at ExceptionTestClass.Main()
 */
 When an error occurs, either the system or
the currently executing application reports
it by throwing an exception that contains
information about the error. After an
exception is thrown, it is handled by the
application or by the default exception
handler.
ERRORS AND EXCEPTIONS
 Run-time errors can occur for a variety of
reasons. However, not all errors should be
handled as exceptions in your code.
 Usage errors. A usage error represents an

error in program logic that can result in an


exception. However, the error should be
addressed not through exception handling
but by modifying the faulty code.
 using System;
 public class Example
 public class Person  {
 {  public static void Main()
 private string _name;  {

 Person p1 = new Person();
 public string Name
 {
 p1.Name = "John";
 get { return _name; }  Person p2 = null;
 set { _name = value; }
 }  // The following throws a
 public override bool Equals(object obj) NullReferenceException.
 {
 Console.WriteLine("p1 = p2: {0}",
 // This implementation contains an error
p1.Equals(p2));
in program logic:
 // It assumes that the obj argument is
 }
not null.  }
 Person p = (Person) obj;
 return this.Name.Equals(p.Name);
 }
 }


 public override bool Equals(object obj)
 {
 // This implementation handles a null obj argument.
 Person p = obj as Person;
 if (p == null)
 return false;
 else
 return this.Name.Equals(p.Name);
 }
 }

 public class Example


 {
 public static void Main()
 {
 Person p1 = new Person();
 p1.Name = "John";
 Person p2 = null;

 Console.WriteLine("p1 = p2: {0}", p1.Equals(p2));


 }
 }
PROGRAM ERRORS
 Program errors. A program error is a run-time error that cannot
necessarily be avoided by writing bug-free code.

 In some cases, a program error may reflect an expected or routine


error condition. In this case, you may want to avoid using exception
handling to deal with the program error and instead retry the
operation.

 For example, if the user is expected to input a date in a particular


format, you can parse the date string by calling the
DateTime.TryParseExact method, which returns a Boolean value
that indicates whether the parse operation succeeded, instead of
using the DateTime.ParseExact method, which throws a
FormatException exception if the date string cannot be converted
to a DateTime value.

 Similarly, if a user tries to open a file that does not exist, you can
first call the File.Exists method to check whether the file exists and,
if it does not, prompt the user whether they want to create it.
SYSTEM FAILURES
 A system failure is a run-time error that cannot
be handled programmatically in a meaningful
way.
 For example, any method can throw an

OutOfMemoryException exception if the


common language runtime is unable to allocate
additional memory.
 Ordinarily, system failures are not handled by

using exception handling. Instead, you may be


able to use an event such as
AppDomain.UnhandledException and call the
Environment.FailFast method to log exception
information and notify the user of the failure
before the application terminates.
FINALLY
 using System;
 public class ExExample
 {
 public static void Main(string[] args)
 {
 try
 {
 int a = 10;
 int b = 0;
 int x = a / b;
 }
 catch (Exception e) { Console.WriteLine(e); }
 finally { Console.WriteLine("Finally block is executed"); }
 Console.WriteLine("Rest of the code");
 }
 }
 Output:
 System.DivideByZeroException: Attempted to

divide by zero.
 Finally block is executed

 Rest of the code


 static void Main(string[] args)
 {
 FileInfo file = null;

 try
 {
 Console.Write("Enter a file name to write: ");
 string fileName = Console.ReadLine();
 file = new FileInfo(fileName);
 file.AppendText("Hello World!")
 }
 catch(Exception ex)
 {
 Console.WriteLine("Error occurred: {0}", ex.Message );
 }
 finally
 {
 // clean up file object here;
 file = null;
 }
 }
 class Program {
 static void Main(string[] args) {
 Console.Write("Please enter a number to divide 100: ");
 try {
 int num = int.Parse(Console.ReadLine());
 int result = 100 / num;
 Console.WriteLine("100 / {0} = {1}", num, result);
 }
 catch(DivideByZeroException ex) {
 Console.Write("Cannot divide by zero. Please try again.");
 }
 catch(InvalidOperationException ex) {
 Console.Write("Invalid operation. Please try again.");
 }
 catch(FormatException ex) {
 Console.Write("Not a valid format. Please try again.");
 }
 catch(Exception ex) {
 Console.Write("Error occurred! Please try again.");
 }
NESTED TRY
 static void Main(string[] args)
 {
 var divider = 0;

 try
 {
 try
 {
 var result = 100/divider;
 }
 catch
 {
 Console.WriteLine("Inner catch");
 }
 }
 catch
 {
 Console.WriteLine("Outer catch");
 }
 }
THROW
 An exception can be raised manually by
using the throw keyword. Any type of
exceptions which is derived
from Exception class can be raised using the
throw keyword.

 Exception objects that describe an error are


created and then thrown with the throw
statement or expression. The runtime then
searches for the most compatible exception
handler.
 static void Main(string[] args)
 {
 Student std = null;
 try
 {
 PrintStudentName(std);
 }
 catch(Exception ex)
 {
 Console.WriteLine(ex.Message );
 }
 Console.ReadKey();
 }

 private static void PrintStudentName( Student std)


 {
 if (std == null)
 throw new NullReferenceException("Student object is null.");

 Console.WriteLine(std.StudentName);
 }
RE-THROWING AN EXCEPTION
 You can also re-throw an exception from the
catch block to pass on to the caller and let
the caller handle it the way they want.
 static void Main(string[] args)
 {
 try
 {
 Method1();
 static void Method2()
 }  {
 catch(Exception ex)
 string str = null;
 {
 Console.WriteLine(ex.StackTrace);
 try
 }  {
 }

 static void Method1()


Console.WriteLine(str[0]);
 {  }
 try  catch(Exception ex)
 {
 Method2();
 {
 }  throw;
 catch(Exception ex)  }
 {
 throw;
 }
 }
 }
CREATING USER-DEFINED
EXCEPTIONS
 User-defined exception classes are derived from
the Exception class.

 Throwing Objects
 You can throw an object if it is either directly or
indirectly derived from the System.Exception class.
 You can use a throw statement in the catch block

 Catch(Exception e)
 {
 ...
 Throw e
 }
 using System;
 class DivByZero : Exception {
 public DivByZero()
 {
 Console.Write("Exception has occurred : ");
 }
 }

 class Program {
 public double DivisionOperation(double numerator, double
denominator)
 {
 // throw exception when denominator value is 0
 if (denominator == 0)
 throw new DivByZero();

 return numerator / denominator;


 }
 // Main
 static void Main(string[] args)
 {
 Program obj = new Program();
 double num = 9, den = 0, quotient;
 try {
 // Code block that may cause an exception
 quotient = obj.DivisionOperation(num, den);

 Console.WriteLine("Quotient = {0}", quotient);


 }
 catch (DivByZero e) {
 Console.Write(e.Message);
 }
 }
 }

You might also like