Module 4-packages and exceptions in java.pptx

0 views 39 slides May 10, 2025
Slide 1
Slide 1 of 39
Slide 1
1
Slide 2
2
Slide 3
3
Slide 4
4
Slide 5
5
Slide 6
6
Slide 7
7
Slide 8
8
Slide 9
9
Slide 10
10
Slide 11
11
Slide 12
12
Slide 13
13
Slide 14
14
Slide 15
15
Slide 16
16
Slide 17
17
Slide 18
18
Slide 19
19
Slide 20
20
Slide 21
21
Slide 22
22
Slide 23
23
Slide 24
24
Slide 25
25
Slide 26
26
Slide 27
27
Slide 28
28
Slide 29
29
Slide 30
30
Slide 31
31
Slide 32
32
Slide 33
33
Slide 34
34
Slide 35
35
Slide 36
36
Slide 37
37
Slide 38
38
Slide 39
39

About This Presentation

Java exceptions ppt


Slide Content

1

2

Module 4 : INTERFACE , EXCEPTION HANDLING, PACKAGES Dept of ISE,DSCE

Chapter 9 : INTERFACE Dept of ISE,DSCE

Defining an Interface An  interface in Java  is a blueprint of a class. It has static constants and abstract methods. The interface in Java is  a mechanism to achieve abstraction . There can be only abstract methods in the Java interface, not method body . It is used to achieve abstraction and multiple inheritance in Java. Java Interface also  represents the IS-A relationship .

Defining an Interface However, an interface is different from a class in several ways, including − You cannot instantiate an interface. An interface does not contain any constructors. All of the methods in an interface are abstract. An interface cannot contain instance fields. The only fields that can appear in an interface must be declared both static and final. An interface is not extended by a class; it is implemented by a class. An interface can extend multiple interfaces.

Declaring Interfaces cntd., The  interface  keyword is used to declare an interface. Here is a simple example to declare an interface − Example 1: /* File name : NameOfInterface.java */ import java.lang.*; // Any number of import statements   public interface NameOfInterface { // Any number of final, static fields // Any number of abstract method declarations\ }

Declaring Interfaces cntd., Interfaces have the following properties − An interface is implicitly abstract. You do not need to use the  abstract  keyword while declaring an interface. Each method in an interface is also implicitly abstract, so the abstract keyword is not needed. Methods in an interface are implicitly public Example 2: interface Callback { void callback(int param); }

Implementing Interfaces Once an interface has been defined, one or more classes can implement that interface . Toimplement an interface, include the implements clause in a class definition, and then create the methods defined by the interface. The general form of a class that includes the implements clause looks like this: class classname [extends superclass ] [implements interface [, interface... ]] { // class-body }

Implementing Interfaces Example: class Client implements Callback { // Implement Callback's interface public void callback(int p) { System.out.println("callback called with " + p); } } It is both permissible and common for classes that implement interfaces to define additional members of their own .

Implementing Interfaces cntd., Example: class Client implements Callback { // Implement Callback's interface public void callback(int p) { System.out.println("callback called with " + p); } void nonIfaceMeth() { System.out.println("Classes that implement interfaces " + "may also define other members, too."); } }

Implementing Interfaces cntd., Example 2: /* File name : Animal.java */ interface Animal { public void eat(); public void travel(); } /* File name : MammalInt.java */ public class MammalInt implements Animal {   public void eat() { System.out.println("Mammal eats"); }   public void travel() { System.out.println("Mammal travels"); }   public int noOfLegs() { return 0; }   public static void main(String args[]) { MammalInt m = new MammalInt(); m.eat(); m.travel(); } } Output: Mammal eats Mammal travels

Implementing Interfaces cntd., When implementation interfaces, there are several rules − A class can implement more than one interface at a time. A class can extend only one class, but implement many interfaces. An interface can extend another interface, in a similar way as a class can extend another class.

Applying Interfaces To understand the power of interfaces, let’s look at a more practical example . Consider class called Stack that implemented a simple fixed-size stack . For example, the stack can be of a fixed size or it can be “growable .” No matter how the stack is implemented, the interface to the stack remains the same. That is, the methods push( ) and pop( ) define the interface to the stack independently of the details of the implementation. Example: module3-fixedstack.docx

Variables in Interfaces You can use interfaces to import shared constants into multiple classes by simply declaring an interface that contains variables that are initialized to the desired values . If an interface contains no methods, then any class that includes such an interface doesn’t actually implement anything. It is as if that class were importing the constant fields into the class name space as final variables. The example below uses this technique to implement an automated “decision maker ”: Module 3-variableOnterface.docx

Chapter 10: Exception Handling Dept of ISE,DSCE

Chapter 10: Exception Handling Dept of ISE,DSCE

Exception-Handling Fundamentals An Exception is an unwanted event that interrupts the normal flow of the program. When an exception occurs program execution gets terminated. If an exception occurs, which has not been handled by programmer then program execution gets terminated and a system generated error message is shown to the user. Exception handling is one of the most important feature of java programming that allows us to handle the runtime errors caused by exceptions.  By handling the exceptions we can provide a meaningful message to the user about the issue rather than a system generated message, which may not be understandable to a user.

Exception-Handling Fundamentals cntd., Why an exception occurs ? There can be several reasons that can cause a program to throw exception. For example: Opening a non-existing file in your program, Network connection problem, bad input data provided by user etc . Examples of system generated exceptions is given below Exception in thread "main" java.lang.ArithmeticException: / by zero at ExceptionDemo.main(ExceptionDemo.java:5) ExceptionDemo : The class name main : The method name ExceptionDemo.java : The filename java:5 : Line number

Exception-Handling Fundamentals cntd., Advantage of exception handling: Exception handling ensures that the flow of the program doesn’t break when an exception occurs. For example, if a program has bunch of statements and an exception occurs mid way after executing certain statements then the statements after the exception will not execute and the program will terminate abruptly . By handling we make sure that all the statements execute and the flow of program doesn’t break.

Types of exceptions There are two types of exceptions in Java: 1)Checked exceptions 2)Unchecked exceptions 1)Checked exceptions All exceptions other than Runtime Exceptions are known as Checked exceptions as the compiler checks them during compilation to see whether the programmer has handled them or not. Example: SQLException, IOException, ClassNotFoundException etc.

Types of exceptions cntd., 2) Unchecked exceptions Runtime Exceptions are also known as Unchecked Exceptions. These exceptions are not checked at compile-time so compiler does not check whether the programmer has handled them or not but it’s the responsibility of the programmer to handle these exceptions and provide a safe exit. Example: ArithmeticException , NullPointerException, ArrayIndexOutOfBoundsException etc.

using try and catch block The try block contains set of statements where an exception can occur . A try block is always followed by a catch block, which handles the exception that occurs in associated try block. A try block must be followed by catch blocks or finally block or both . Syntax of try block try { //statements that may cause an exception }

using try and catch block cntd., Catch block A catch block is where you handle the exceptions, this block must follow the try block. A single try block can have several catch blocks associated with it. You can catch different exceptions in different catch blocks. When an exception occurs in try block, the corresponding catch block that handles that particular exception executes. For example if an arithmetic exception occurs in try block then the statements enclosed in catch block for arithmetic exception  executes. Syntax of try catch in java try{ //statements that may cause an exception } catch (exception(type) e(object )) ‏ { //error handling code }

using try and catch block cntd., 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. Example: class Exc2 { public static void main(String args[]) { int d, a; try { // monitor a block of code. d = 0; a = 42 / d; System.out.println("This will not be printed."); } catch (ArithmeticException e) { // catch divide-by-zero error System.out.println("Division by zero."); } System.out.println("After catch statement."); } } Output: Division by zero. After catch statement.

Nested try statements When a  t ry catch block is present in another try block then it is called the nested try catch block . Syntax of Nested try Catch //Main try block try { statement 1; statement 2; //try-catch block inside another try block try { statement 3 ; statement 4; //try-catch block inside nested try block try { statement 5; statement 6; }

Cntd., catch(Exception e2) { //Exception Message } } catch(Exception e1) { //Exception Message } } //Catch of Main(parent) try block catch(Exception e3) { //Exception Message }

Example- nested try statements c lass NestedTry {      // main method      public static void main(String args[])      {          // Main try block          try {              // initializing array              int a[] = { 1 , 2 , 3 , 4 , 5 };                 // trying to print element at index 5              System.out.println(a[ 5 ]);                 // try-block2 inside another try block              try {                     // performing division by zero                  int x = a[ 2 ] / ;              }               catch (ArithmeticException e2) {                  System.out.println( "division by zero is not possible" );              }          }          catch (ArrayIndexOutOfBoundsException e1) {              System.out.println( "ArrayIndexOutOfBoundsException" );              System.out.println( "Element at such index does not exists" );          }      }      // end of main method } Output: ArrayIndexOutOfBoundsException Element at such index does not exists

throw The Java throw keyword is used to explicitly throw an exception. We can throw either checked or uncheked exception in java by throw keyword. The throw keyword is mainly used to throw custom exception . The syntax of java throw keyword is given below . throw  exception;   Example: throw   new  IOException("sorry device error);  

Throw Example 1: public class TestThrow1{      static void validate(int age){        if(age<18)         throw new ArithmeticException("not valid");        else         System.out.println("welcome to vote");      }      public static void main(String args[]){         validate(13);         System.out.println("rest of the code...");     }   }   Output: Exception in thread main java.lang.ArithmeticException:not valid

Throw Example 2 // Java program that demonstrates the use of throw class ThrowExcep {      static void fun()      {          try          {              throw new NullPointerException( "demo" );          }          catch (NullPointerException e)          {              System.out.println( "Caught inside fun()." );              throw e; // rethrowing the exception          }      }         public static void main(String args[])      {          try          {              fun();          }          catch (NullPointerException e)          {              System.out.println( "Caught in main." );          }      } } . Output: Caught inside fun (). Caught in main

throws throws is a keyword in Java which is used in the signature of method to indicate that this method might throw one of the listed type exceptions. The caller to these methods has to handle the exception using a try-catch block.  Syntax :    type method_name(parameters) throws exception_list exception_list is a comma separated list of all the exceptions which a method might throw To prevent the compile time error we can handle the exception in two ways:  By using try catch By using throws keyword We can use throws keyword to delegate the responsibility of exception handling to the caller (It may be a method or JVM) then caller method is responsible to handle that exception .  

Throws cntd., // Java program to illustrate error in case // of unhandled exception class tst {      public static void main(String[] args)      {          Thread.sleep( 10000 );          System.out.println( "Hello All" );      } } Output: error: unreported exception InterruptedException; must be caught or declared to be thrown

Throws cntd., //Java program to illustrate throws class tst {     public static void main(String[] args)throws InterruptedException     {         Thread.sleep(10000);         System.out.println("Hello All");     } } Output: Hello All

Throws cntd., // Java program to demonstrate working of throws 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.");         }     } } Output: Inside fun(). caught in main.

Throws cntd., Important points to remember about throws keyword:   throws keyword is required only for checked exception and usage of throws keyword for unchecked exception is meaningless. throws keyword is required only to convince compiler and usage of throws keyword does not prevent abnormal termination of program. By the help of throws keyword we can provide information to the caller of the method about the exception.

finally Just as final is a reserved keyword, so in same way finally is also a reserved keyword in java i.e, we can’t use it as an identifier. The finally keyword is used in association with a try/catch block and guarantees that a section of code will be executed, even if an exception is thrown.

Finally Example / A Java program to demonstrate finally. class Geek {      // A method that throws an exception and has finally.      // This method will be called inside try-catch.      static void A()      {          try {              System.out.println( "inside A" );              throw new RuntimeException( "demo" );          }          finally          {              System.out.println( "A's finally" );          }      }   

Finally Example cntd., // This method also calls finally. This method      // will be called outside try-catch.      static void B()      {          try {              System.out.println( "inside B" );              return ;          }          finally          {              System.out.println( "B's finally" );          }      }      public static void main(String args[])      {          try {              A();          }          catch (Exception e) {              System.out.println( "Exception caught" );          }          B();      } } Output: inside A A's finally Exception caught inside B B's finally
Tags