Thursday, September 28, 2023

Exception 5 keywords in 1 program

 class ThrowsExecp {

    static void fun() throws IllegalAccessException

    {

        System.out.println("Inside fun(). ");

        throw new IllegalAccessException("demo");

    }

 

    public static void main(String args[])

    {

        try {

            fun();

        }

        catch (IllegalAccessException e) {

            System.out.println("caught in main.");

        }

finally {

      System.out.println("This is the finally block");

       }

    }

}

Important topics for Final exams

Important topics for Final  exams


 Explain about  data types and their sizes

java program to apply addition of  two three dimensional matrices

Explain method overriding

Explain method overloading

Explain  differences between method overriding and method overloading

Explain  constructor and its types

Explain  copy constructor 

Explain inheritance and types

differences between this and super

super class reference variable referring sub class object  Explain 

Write a program in Java to find  prime number where n is any integer and read input from the user


Explain  about single and multiple dimensional array.

how to create packages and their usage

various uses of ‘final’ keyword

Explain  about control statements

Explain  about  for each loop in java

explain about call by value and call by reference 

Explain about Dynamic method dispatch

Explain  importance of exception handling

Explain   checked and unchecked exceptions 

 Explain   keywords of exception handling

how to create your own exception

 

Wednesday, September 27, 2023

Exception notes

 Exception Handling:

An exception is an abnormal condition that arises in a code sequence at run time. Exception is a run time error.

Java and other programming languages have mechanisms for handling exceptions that you can use to keep your program from crashing.  In Java, this is known as catching an exception/exception handling.

When java interpreter encounters an error, it creates an exception object and throws it( informs us that an error occurred).

If the exception object is not caught and handled properly, the interpreter will display a message and stops the program execution.

If we want the program to continue with the execution of the remaining code, then we should try to catch the exception object thrown by the error condition and then display an appropriate message for taking corrective actions.


Errors are broadly classified into two categories.

1. Compile time exception(error)

2. Run Time exception(error)


Compile-time errors:

All syntax errors will be detected and displayed by the java compiler and therefore these errors are known as compile-time errors.

Whenever the compiler displays an error, it will not create the .class file.


Run-time errors:

Sometimes a program may compile successfully creating the .class file but may not run properly because of abnormal conditions.

Common run-time errors are

o The file you try to open may not exist.

o Dividing an integer by Zero.

o Accessing an element that is out of the bonds of an array type.

o Trying to store a value into an array of an incompatiable class or type.

o Trying to cast an instance of a class to one of its subclasses.

o And many more……………..



Each exception is a class, part of java.lang package and it is derived from Throwable class.


Java Exception handling is managed by 5 keywords.

1. try

2. catch

3. throw

4. throws

5. finally


If these abnormal conditions are not handled properly, either the program will be aborted or the incorrect result will be carried on causing more and more abnormal conditions.


Example to see what happens if the exceptions are not handled:

class NoException 

{

public static void main(String[] args) 

{

int no=10;

int r=0;

r=no/0;

System.out.println("Result is:"+r);

}

}

The above program gives the following error:

Exception in thread "main" java.lang.ArithmeticException: / by zero

        at NoException.main(NoException.java:8)


In the above program the error is handled by the default exception handler which is provided by java run-time system.


If the exception is handled by the user then it gives two benefits.

1. Fixes the error.

2. Avoids automatic termination of program.


Syntax:

       try

       {

        statement;   // generates exception

       }

       catch(Exception-type e)

       {

        statement;   // process the exception

       } 

Java uses a keyword try to preface a block of code that is likely to cause an error and “throw” an exception.

A catch block is defined by the keyword catch “catches” the exception “thrown” by the exception block.

Catch block should be immediately after the try block.

try block can have one or more statements that could generate an exception.

If any one statement generates an exception, the remaining statements in the block are skipped and control jumps to the catch block that is placed next to the try block.

The catch block too can have one or more statements that are necessary to process the exception.

Every try block should be followed by at least one catch statement.

Catch statement works like a method definition, contains one parameter, which is reference to the exception object thrown by the try block.


Program:

// program name:..\atish\java_new\core\exp\TryCatch.java

class TryCatch

{

  public static void main(String[] args) 

  {

    int a=10;

    int b=5;

    int c=5;

    int r;


    try

    { r=a/(b-c); // exception here

      System.out.println("This will not be executed......");

    }

    catch(ArithmeticException e)

    { System.out.println("Cannot divide by 0....."); }

    System.out.println("After catch statement.....");

  }

}

Note: Once an exception is thrown, control is transferred to catch block and never returns to try block again.


***Statements after the exception statement(try block) never get xecuted.


Multiple catch statements:

Syntax:


try

{

 statement;

}

catch(Exception-type 1 e)

{

 statement;  // process exception type 1

catch(Exception-type 2 e)

{

 statement;  // process exception type 2

catch(Exception-type N e)

{

 statement;  // process exception type N

When an exception in a try block is generated, java treats the multiple catch statements like cases in switch statement.

The first statement whose parameter matches with the exception object will be executed, and the remaining statements will be skipped.

Code in the catch block is not compulsory.

o catch (Exception e){}

o the catch statement simply ends with a curly braces( {} ), which does nothing, this statement will catch an exception and then ignore it.


import java.util.*;


class MultiCatch

{

 public static void main(String args[])

 {

  int no,d,r;

  no=d=r=0;


 try

 {

  no=Integer.parseInt(args[0]);

  d=Integer.parseInt(args[1]);


  r=no/d;

  System.out.println("Result :"+r);

 }

 catch (NumberFormatException nf)

 {

   System.out.println(nf);

 }


catch (ArrayIndexOutOfBoundsException ai)

 {

 System.out.println(ai);

 }

 catch (ArithmeticException ae)

 {

  System.out.println(ae);

 }

 }

}


Finally:


Java supports another statement known as finally that can be used to handle an exception that is not caught by any one of the previous catch statements.

Finally block can be used to handle any exception generated with in a try block. 

It may be added immediately after the try block or the last catch block.


Syntax 1:                                    syntax 2:

try                                          try

{                                            {   

 statements;                                  statements;

}                                            }

finally                                      catch(..)

{                                            {

 statements;                                  statements;

}                                            }

                                             catch(..)

                                             {

                                              statements;

                                             }

                                             finally

                                             {

                                              statements;

                                             }

Note:

When a finally block is defined, this is guaranteed to execute, regardless whether exception is thrown or not.

Finally block is mainly used to close the files, releasing system resources.


throws clause:

Runtime Exceptions are referred to as unchecked exceptions. All other exceptions are checked exceptions, they don’t derive from java.lang.RuntimeException.

A Checked exception must be caught some where in the program code.

If you invoke a method that throws a checked exception but you don't catch the checked exception somewhere, your code will not compile. That's why they are called checked exceptions.

The compiler checks to make sure that they are handled or declared.


Syntax:


<return type> method name([parameters-list]) throws exp 1,exp 2,…………

Ex: 1

        import java.io.*;

        class ThrowsTest

        {

         public static void main() throws EOFException

         {

          throw new EOFException();

          }

         }


Ex: 2

import java.io.*;

 class Test

 {

  void doWork() throws IOException


  {

   throw new IOException();

  }

 }


 class ThrowsTest1

 {

  public static void main(String args[])  throws IOException

  {

   Test t1=new Test();

   t1.doWork();

  }

  }



Printing information about an exception:

it is useful to discover the cause of an exception. When you know the cause of an exception, it makes easier to fix programming bugs as soon as they discovered.

As all the exception classes are derived from Throwable, they all support the following methods provided by the Throwable.


Nested try statements:

Try statements can nested.


// program name:..\atish\java_new\core\exp\NestedTry.java

class NestedTry

 {

   public static void main(String args[])

    {

     try

     {

      int a=args.length;

      int b=10/a; // if no command line argument is passed

                 // it generates divide-by-zero exception

      System.out.println("a="+a);

      try

      {

       if(a==1)

         a=a/(a-a); // divide-by-zero exception

       else

           if(a==2)

            {

             int c[]={1};

             c[5]=99; // generates out of bounds exception

             }

        }

        catch(ArrayIndexOutOfBoundsException e)

        { System.out.println("Array index out-of-bounds:"+e); }

      }

      catch(ArithmeticException e)

      { System.out.println("Divide by 0:"+e); }

    }

  }


Rethrowing the exceptions:


class ReThrow

{

 static void test()

 {

  try

  {

   throw new NullPointerException("Testing..");

   }

  catch(NullPointerException e)

  {

   System.out.println("Caught inside test method..");

   throw e; // rethrow the exception

  }

 }


  public static void main(String args[])

  {

   try

   {

    test();

    }

   catch(NullPointerException e)

   {

    System.out.println("Recaught..:"+e);

   }

  }

 }            


Example NullPointer Exception:

class Test

{

 int no=10;

 void disp()

 { System.out.println("no is:"+no);

    }

}

class NPE

{

 public static void main(String args[])

 {

  Test t=new Test();

  t=null;

  try{

  t.disp();

  }

  catch(NullPointerException np)

  { np.printStackTrace();

    }

 }

}









Thursday, September 14, 2023

Checked Exceptions & Unchecked Exceptions

                                                  Exceptions 

 

Exceptions are a mechanism used to handle unexpected or exceptional situations that can occur during the execution of a program. Java categorizes exceptions into two main types: checked exceptions and unchecked exceptions (also known as runtime exceptions). These two categories serve different purposes and have different characteristics.

 

Checked Exceptions:

 Checked exceptions are exceptions that the Java compiler requires you to handle explicitly in your code. This means that if a method can potentially throw a checked exception, you must either catch and handle that exception using a

try-catch block or declare that the method throws the exception using the throws keyword in its method signature.

Common examples of checked exceptions include IOException, SQLException, and ClassNotFoundException.

Checked exceptions typically represent external problems or issues that your program may encounter during its execution, such as file I/O errors or database connection problems. Handling these exceptions ensures that your program can gracefully recover from these situations or report errors to the user.

Example of handling a checked exception:

code:

try {

// Code that may throw a checked exception FileInputStream file = new FileInputStream("example.txt");

} catch (IOException e) {

// Handle the exception

System.out.println("An error occurred: " + e.getMessage());

}

 

Unchecked   Exceptions (Runtime Exceptions):

 Unchecked exceptions, also known as runtime exceptions, are exceptions that the compiler does not require you to handle explicitly. These exceptions usually

indicate programming errors or issues that can be avoided through proper coding practices.

Common examples of unchecked exceptions include NullPointerException, ArrayIndexOutOfBoundsException, and ArithmeticException.

Unchecked exceptions typically occur due to logical errors in the code, such as attempting to access a null reference or dividing by zero. While you are not forced to handle them, it's still a good practice to do so when possible to make your code more robust.

      

Example of an unchecked exception:

 int[] numbers = {1, 2, 3};

int result = numbers[5]; // This will throw an ArrayIndexOutOfBoundsException at runtime

 

In summary, the key difference between checked and unchecked exceptions in Java is that checked exceptions must be explicitly handled or declared, while unchecked exceptions (runtime exceptions) do not require explicit handling but should still be addressed when possible. Effective exception handling is an essential part of writing reliable and robust Java programs, as it allows you to gracefully handle unexpected situations and provide meaningful feedback to users.

 

 

 

**** Difference between checked                      and unchecked exceptions****


Aspect

Checked Exceptions

Unchecked Exceptions

Declaration in Code

Must be declared using the throws clause in the method signature or handled using a try-catch block.

Optional to declare or handle. You can still use a try-catch block, but it's not required.


Examples

IOException, SQLException, ClassNotFoundException

NullPointerException, ArrayIndexOutOfBoundsExceptio n, IllegalArgumentException

Compiler Enforcement

The compiler enforces handling or declaring checked exceptions at compile-time.

The compiler does not enforce handling or declaring unchecked exceptions at compile-time.

Handling Requirement

Mandatory handling or declaration, either through a try-catch block or by propagating the exception using the throws clause.

Optional handling; you can choose whether or not to handle unchecked exceptions.

Checked by Compiler

Checked exceptions are checked by the compiler to ensure that they are properly handled or declared

Unchecked exceptions are not checked by the compiler, meaning that the compiler does not enforce handling or declaration.

Extending Throwable

Subclasses of Exception (excluding RuntimeException) and its subclasses are considered checked exceptions.

Subclasses of RuntimeException and its subclasses are considered unchecked exceptions.

Inheritance Hierarchy

Checked exceptions are typically further up the exception hierarchy and inherit from Exceptions.

Unchecked exceptions are typically further down the hierarchy and inherit from RuntimeException

Propagating Exceptions

Checked exceptions need to be declared using the throws keyword in the method signature if they are not handled locally.

Unchecked exceptions do not need to be declared using the throws keyword, even if they are not handled locally.

Try- Catch Block Requirement

Required for checked exceptions if you don't use the throws clause for declaration.

Optional for unchecked exceptions; you can still use try-catch blocks if desired.


 

 

       *****Program for Checked Exception in Java*******

 

 

public class CheckedException {

public static void main(String[] args) { int dividend = 10;

int divisor = 0;

 

try {

int result = dividend / divisor; System.out.println("Result: " + result);

} catch (ArithmeticException e) {

// Handle the checked exception (ArithmeticException) System.err.println("An error occurred: " + e.getMessage());

}

}

}

 

 

 

Output:

An error occurred: / by zero

 

       *****Program for Unchecked Exception in java*****

 

public class UncheckedExceptionExample { public static void main(String[] args) {

int[] numbers = { 1, 2, 3, 4, 5 };

 

// Attempt to access an index that is out of bounds int index = 10;

int value = numbers[index];


System.out.println("Value at index " + index + ": " + value); // This line won't be reached

}

}

Output:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 10 out of bounds for length 5

at UncheckedExceptionExample.main(UncheckedExceptionExample.java:8)

 

Exception-Handling Fundamentals

                   Exception-Handling Fundamentals

                       Java exception handling is managed via five keywords: try, catch, throw, throws, and finally. Briefly, here is how they work. Program statements that you want to monitor for exceptions are contained within a try block. If an exception occurs within the try block, it is thrown. Your code can catch this exception (using catch) and handle it in some rational manner. System-generated exceptions are automatically thrown by the Java run-time system. To manually throw an exception, use the keyword throw. Any exception that is thrown out of a method must be specified as such by a throws clause. Any code that absolutely must be executed after a try block completes is put in a finally block.

Using try and catch :

                       The default exception handler provided by the Java run-time system is useful for debugging, you will usually want to handle an exception yourself. Doing so provides two benefits. First, it allows you to fix the error. Second, it prevents the program from automatically terminating. To guard against and handle a run-time error, simply enclose the code that you want to monitor inside a try block. Immediately following the try block, include a catch clause that specifies the exception type that you wish to catch. To illustrate how easily this can be done, the following program includes a try block and a catch clause that processes the ArithmeticException generated by the division-by-zero error:

class Exc2 { public static void main(String args[])

 { int d, a; 

try {

 d = 0; a = 42 / d; 

System.out.println("This will not be printed."); 

catch (ArithmeticException e) 

 System.out.println("Division by zero."); 

}

 System.out.println("After catch statement."); 

} }

This program generates the following output: 

Division by zero.

 After catch statement :

                         Notice that the call to println( ) inside the try block is never executed. Once an exception is thrown, program control transfers out of the try block into the catch block. Put differently, catch is not “called,” so execution never “returns” to the try block from a catch. Thus, the line “This will not be printed.” is not displayed. Once the catch statement has executed, program control continues with the next line in the program following the entire try/catch mechanism.

Throw :

                         Here it  have only been catching exceptions that are thrown by the Java run-time system. However, it is possible for your program to throw an exception explicitly, using the throw statement. 

The flow of execution stops immediately after the throw statement; any subsequent statements are not executed. The nearest enclosing try block is inspected to see if it has a catch statement that matches the type of exception. If it does find a match, control is transferred to that statement. If not, then the next enclosing try statement is inspected, and so on. If no matching catch is found, then the default exception handler halts the program and prints the stack trace

class ThrowDemo 

static void demoproc() 

{

 try 

{

 throw new NullPointerException("demo");

 } 

catch(NullPointerException e)

 {

 System.out.println("Caught inside demoproc."); 

throw e;

}

 }

Throws :

                                If a method is capable of causing an exception that it does not handle, it must specify this behavior so that callers of the method can guard themselves against that exception. You do this by including a throws clause in the method’s declaration. A throws clause lists the types of exceptions that a method might throw. This is necessary for all exceptions, except those of type Error or RuntimeException, or any of their subclasses. All other exceptions that a method can throw must be declared in the throws clause.

// This program contains an error and will not compile.

 class ThrowsDemo

 { 

static void throwOne() 

System.out.println("Inside throwOne."); 

throw new IllegalAccessException("demo");

 } 

public static void main(String args[]) 

throwOne();

 }

 }

Finally :

                          When exceptions are thrown, execution in a method takes a rather abrupt, nonlinear path that alters the normal flow through the method. Depending upon how the method is coded, it is even possible for an exception to cause the method to return prematurely. This could be a problem in some methods. For example, if a method opens a file upon entry and closes it upon exit, then you will not want the code that closes the file to be bypassed by the exception-handling mechanism. The finally keyword is designed to address this contingency.

Here is an example program that shows three methods that exit in various ways, none without executing their finally clauses: 

// Demonstrate finally.

 class FinallyDemo 

// Through an exception out of the method.

 static void procA()

 { 

try 

{

 System.out.println("inside procA"); 

throw new RuntimeException("demo"); 

finally 

System.out.println("procA's finally"); 

}


Tuesday, September 12, 2023

Abstract class Program which covers many concerpts

 klct class Student 

{

     int id;

    String name;

    int marks;

    Student()

    {

        id = 10;

        string name = "yourname";

        marks = 85;

    }

    Student(int i, String n, int m)

    {

        id = i;

        name = n;

        marks = m;

    }

    Student(Student s)

    {

        id = s.id;

        name = s.name;

        marks = s.marks;

    }

    abstract void displayName();

    void displayInfo() 

    {

        System.out.println("Student id: " + id);

        System.out.println("Student name: " + name);

        System.out.println("Student marks: " + marks);

    }

}

class Student1 extends Student

 {

    void displayName()

    {

        System.out.println("Student1 name: " + name);

    }

 }

class Student2 extends Student

 {

    void displayName() 

    {

        System.out.println("Student2 name: " + name);

    }

 }

class Student3 extends Student

 {

   

    String gender;


    Student3()

    {

        super();

    }

    Student3(int i, String n, int m, String g)

    {

        super(i, n, m);

        gender = g;

    }

    Student3(Student3 s) 

    {

        super(s);

        gender = s.gender;

    }

    void displayName()

    {

        System.out.println("Student1 name: " + name);

    }

   

}

public class StudentDemo

{

    public static void main(String[] args)

    {

        Student3 g = new Student3(1, "your name", 88, "f");

        Student A;

        A = g;

        A.displayInfo();

        Student1 obj1 = new Student1();

        Student2 obj2 = new Student2();

        Student3 ob1 = new Student3();

        Student3 ob2 = new Student3(1,"name",92,"f");

        Student3 ob3 = new Student3(ob1);

    

        //System.out.println("info="+ob1.gender);

    

        System.out.println("gender="+ob2.gender);

        //System.out.println("info="+ob3.gender);

          Student ref;

        ref = obj1;

        ref.displayName();

        ref.displayInfo();

        ref = obj2;

        ref.displayName();

        ref.displayInfo();

    }

}


Machine Learning Course Assignments 2024(Dec)

 Machine Learning Course Assignments 2024 1)   Explain the concept of "generalization" in machine learning. Why is it a central go...