Sunday, 19 April 2015

Exception Handling C #

Basics : 
1. Exceptions are objects. They are used to handle code flow , where error might occur.
2. Exceptions are throw-n and catch -ed.
3. They are throm from try-block ,and catch-ed in catch block.

4. If an exception is thrown from line x , then rest of lines ( > x) in that try block are not executed.

try {
    Exception e = new Exception(" My first exception. ");
    throw e;
/* Followings will not be executed.*/
    TextReader reader = new StreamReader("FileName.txt");
    string line = reader.ReadLine();
    Console.WriteLine(line);
    reader.Close();
}
catch ( FileNotFoundException fnfe)
{
     Console.WriteLine(" This is printed when you try to open non-existing file");
}
catch ( Exception ex)
{
     Console.WriteLine( ex.message);
}

5. Base class Exceptions catches all derived class exceptions.
6. All classes derive directly or in-directly from class : Exception.

7. When flow enters a catch block , it will ignore other catch blocks. Thats why "FileNotFoundException" is put before "Exception" in above code. ( Point 6).

8. If u don't catch exception ,   it will be caught by CLR : Common Language Runtime.
9. Exception handler is code which catches Exception-s.

10. Funtions are pushed on stack when they are called , and poped out , when they finish.
    If a function generates an exception , then CLR starts looking for exception handler , starting from top of the stack.

What Exception Contains :

1. Message : 
2. Stack-trace : functions on stack at time when Exception is throw-n.
    Stack-trace contains :
at <namespace>.<class>.<method>  in  <Source file>.cs:line <line>
line number is displayed only when class is compiled with debug information. Thats why line number are not shown for .Net Assemblies.

3. If exception arises within constroctor , then stack-trace displays ".ctor" instead of constructor name.


Exception Hierarchy :

class ApplicationException :  Exception { ...  } // Exceptions thrown by applications developed by us.

class SystemException : Exception { ... } // Exceptions thrown by runtime.

================ Primitive Types =====================
Name               Type              Size       Default value
Byte              Value             1 byte          0
Short             Value             2 bytes         0
Integer           Value             4 bytes         0
Long              Value             8 bytes         0

Single            Value             4 bytes         0f
Double            Value             8 bytes         0f

Boolean           Value                            false

Date              Value                          01/01/0001 12:00:00AM

Char              Value                           CharW(0)

String           Reference                          null

============ Angles ========================
GameObject go = .....;
go.transform.eulerAngles = new Vector3(x,y,z);
x = clockwise angle in Y-Z plane , when viewed from right side.
y = clockwise angle in X-Z plane , when viewed from top side.
z = anti-clockwise angle in X-Y plane , when viewed from front side.

====================================================== Create Primitive type and attach component and set position ===============================

GameObject[] allObjects =
(GameObject[]) GameObject.FindSceneObjectsOfType(typeof(GameObject));
foreach(GameObject g in allObjects) {...}
Debug.DrawLine(this.transform.position,closestGameObject.transform.position);

Entry points : Start() , Update() , Awake (), OnEnable (), Start (), OnApplicationPause (), Update (), FixedUpdate (), and LateUpdate ();
When the object is destroyed, OnDestroy() is called

GameObject box = GameObject.CreatePrimitive (PrimitiveType.Cube);  /* Creates new primitive types.*/
box.transform.position = new Vector3 (numCubes * 2.0f, 0f, 0f); /* Sets position of object in screen.*/

Here is an enum called PrimitiveType. Inside this is Sphere, Capsule, Cylinder, Cube, and Plane.
we can attach same script to multiple objects.

start()
{
    MyTree tree = (MyTree)GameObject.FindObjectOfType<MyTree> (typeof(MyTree));
    Debug.Log(tree.gameObject.name); // This will be object's name ( like Tree 4) to which component is attached, not class's name.
}

ArrayList list = new ArrayList();
list.Add(1);
list.Add("this");
list.Add(1.0);
list.Add(1.0f);

/*
GameObject is Object.
GameObject is addition of many Component.
Component is Object. public class Component : Object

Ex. If a script Child.cs is attached to a GameObject Cube, then class Child ( written inside Child.cs ) will be a Component of Cube. And that can be get in code via :
    Component com = go.getComponent( typeof( Child));
Here typeof applies even on class.
*/

bool Apressed = Input.getKey(KeyCode.A); /* returns true for the period, during which A is kept PRESSED., else return false.*/

/* In C# static variables can NOT be accessed via an instance of that class. PLEASE SEE IT AND VERIFY*/

to move object update transform.position in update().

====================== Find distance and direction ===============
    GameObject tank = ameObject.Find ("Tank");
    Vector3 direction = (tank.transform.position - transform.position).normalized;
        Vector3 distance = (tank.transform.position - transform.position).magnitude;
==================================================================
When a variable is declared using one of the basic, built-in data types or a user defined structure, it is a value type. An exception is the string data type, which is a reference type.
In contrast, a reference type, such as an instance of a class or an array, is allocated in a different area of memory called the heap.
In the example below, the space required for the ten integers that make up the array is allocated on the heap.

int[] numbers = new int[10];

This memory isn't returned to the heap when a method finishes;
 it's only reclaimed when C#'s garbage collection system determines it is no longer needed. There is a greater overhead in declaring reference types, but they have the advantage of being accessible from other classes.

class Fake
{
    public int b;
    print(b); // OK , prints 0; coz its primitive type so memory is alloted . Since its global , hence assigned to 0.
    foo() {
        int a;
        print(a); // Error : Use of un-assigned local variable a;
    }
}

class Faker
{
    Fake f;
   
    void start(){
        print(f.b); // NULL Reference exception. object f do not exists. ( only reference exists which is assigned to null, since its global.)
       
        Fake aF;
        print(aF.b); // Compile time error : Use of unassigned local variable.
    }
}

================= new () 's uses ========================

 class A {...}
 A aA; // memory alloted only for reference , object is not created.
 aA = new A(); // Object is created . Constructor is called.

 class Base
 {
    public foo() { }
 }
 class Derived: Base{
    new public foo() { print("new");} // without new, this will compile with compiler warning.
 }
 =======================================================
 main tujhe kal bhi pyar karta tha ......

 * Vector3 is structure , hence when assigned , its copied by value.
 * Classes are copied by reference.




=================      Aiming =============================================
 Vector3 mousePosition = Input.mousePosition;
 Debug.Log(transform.localRotation);
 Debug.Log(transform.eulerAngles);

 SAVE PROJECT'S COPY AT EACH MILESTONE, COVERED. ( so that if something goes wrong , we can start again from last firm ground.)

  in concept : transform.rotation = transform.localRotation + parent.rotation;
 
  to control rotation via mouse position :
  Vector3 mousePos = Input.mousePosition;
        float x = mousePos.x;
        float y = mousePos.y;
  transform.eulerAngles = new Vector3 (y*0.1f, x *0.1f, 0);
 
  another way :
  Input manager location : Edit -> Project Settings -> Input
  Then all information is shown in inspector panel.
        x += Input.GetAxis ("Mouse X");
        y += Input.GetAxis ("Mouse Y");
        transform.eulerAngles = new Vector3 (y, -x, 0);
    Please note that Input.GetAxis ("Mouse X") gives us the difference between last mouse position and current mouse position, Not the absolute values.
   
========================    Moving    ==========================================
    void Update () {
        if (Input.GetKey (KeyCode.W) || Input.GetKey(KeyCode.UpArrow)) {
            transform.position +=  transform.forward * 0.1f;
        }
        if (Input.GetKey (KeyCode.S) || Input.GetKey(KeyCode.DownArrow)) {
            transform.position -= transform.forward * 0.1f;
        }
        if (Input.GetKey (KeyCode.A) || Input.GetKey(KeyCode.LeftArrow)) {
            transform.position -= transform.right*0.1f;
        }
        if (Input.GetKey (KeyCode.D) || Input.GetKey(KeyCode.RightArrow)) {
            transform.position += transform.right * 0.1f;
        }
   
 ========================================================= calculate angle ==============================
 var targetDir = target.position - transform.position;
        angleBetween = Vector3.Angle (transform.forward, targetDir);
       
 ==============  error 1 =============
 void Start () {
        GameObject boundryUnit = GameObject.CreatePrimitive (PrimitiveType.Cube);
        boundryUnit.transform.eulerAngles.x = 30;
    }
    error: can not modify a value type return value of "UnityEngine.Transform.eulerAngles". Consider storing the value in a temporary variable.
    Solution : x of vector have only "get" property.
     void Start () {
        GameObject boundryUnit = GameObject.CreatePrimitive (PrimitiveType.Cube);
        boundryUnit.transform.eulerAngles = new Vector3(30,0,0);
        //boundryUnit.transform.eulerAngles.x = 50; This will again produce same error as above.
    }
 ============================================= make boundry line =============
     totalArcs = totalArcs * (int)radius;
        float angle = (2* Mathf.PI) / (totalArcs);
        for (int i = 1; i <= totalArcs; i++) {
            GameObject boundryUnit = GameObject.CreatePrimitive (PrimitiveType.Cube);
            boundryUnit.transform.eulerAngles = new Vector3(0 , - (i * 360/totalArcs) , 45);
            boundryUnit.transform.position = new Vector3(radius * Mathf.Cos(angle*i) , 0 , radius * Mathf.Sin(angle*i));
            boundryUnit.transform.localScale = new Vector3(scale , scale , 2*scale);
            Renderer rend = boundryUnit.GetComponent<Renderer>();
            if(i == 1) rend.material.SetColor("_Color" , Color.blue);
            else if(i == 8) rend.material.SetColor("_Color" , Color.red);
            else rend.material.SetColor("_Color" , Color.green);
            // add component : go.AddComponent(typeof(ZombieData));  // here ZombieData is a class.
        }
=================================================================================    define array =========
public int[] Primes = new int[]{1, 3, 5, 7, 11, 13, 17};
====================================    setting random values ========================
 Vector3 v = new Vector3();
v.x = Random.Range(-10, 10);
v.z = Random.Range(-10, 10);
 ============================  instantiate gameObject ============
 public GameObject PuzzlePiece; // Drag sphere to this variable.
 for (int x = 0; x < 6; x++) {
            for ( int y = 0 ; y < 6 ; y++) {
                GameObject go = GameObject.Instantiate(PuzzlePiece);
                go.transform.position = new Vector3(x , y , 0);
                Grid[x , y] = go;
            }
        }

 Sphere will be created in 6x6 grid. => By default scale of sphere is 1x1x1. Thats why they did not overlapped.
 ==================  pick a puzzlePiece with mouse. ===========================
 Perspective view : lines will converge to a point in space.
 Orthographic projection : Lines where mouse appears in the game will be parallel to what camera is looking at.
 Vector3 mouse = Input.mousePosition; // (0,0,0) will be down left corner of screen.
        Vector3 mousePos = Camera.main.ScreenToWorldPoint( mouse); // (0,0,0) will be somewhere inside screen.
        Debug.DrawLine (Vector3.zero, mousePos);