0% found this document useful (0 votes)
5 views

Lecture 12

The document provides a comprehensive overview of exception handling in Java, detailing its definition, types, advantages, and syntax for implementing exception handling using keywords like try, catch, and finally. It also covers common exceptions, user-defined exceptions, and the distinction between checked and unchecked exceptions. Additionally, it includes code examples to illustrate exception handling mechanisms and the use of methods for managing exceptions.

Uploaded by

absshuvo1100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views

Lecture 12

The document provides a comprehensive overview of exception handling in Java, detailing its definition, types, advantages, and syntax for implementing exception handling using keywords like try, catch, and finally. It also covers common exceptions, user-defined exceptions, and the distinction between checked and unchecked exceptions. Additionally, it includes code examples to illustrate exception handling mechanisms and the use of methods for managing exceptions.

Uploaded by

absshuvo1100
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Lecture Outline:

1.Introduction to Exception Handling


2.Declaration of Exception Handling
3.Exception Types
4.Common Exceptions
5.Advantages of Exception Handling
6.User Defined Exception
Check the code:
Public class Main{
Public static void main(String [] args) {
Int a = 1;
Int b= 0;
Int result = divide(a,b);
System.out.println(“Result: ” +result);
}
Public static int divide (int a, int b) {
Return a/b;
}
}
Introduction to Exception Handling:-
What is Exception?
❑ An exception is an abnormal condition that arises in a code sequence at run time. In other words, an
exception is a runtime error.
❑ See the following program:

❑ After execution:

More about Exception


❑ Some exceptions are caused by user error, others by programmer error, and others by physical
resources that have failed in some manner.
❑ So, exception may occur whenever:
❑ A user enters an invalid data. (Example: InputMismatchException, ArithmeticException).
❑ A file that needs to be opened cannot be found. (Example: FileNotFoundException,
ClassNotFoundException).
❑ A network connection has been lost in the middle of communications or the JVM has run out of
memory. (Example: SocketException, ConnectException).
❑ A Java exception is an object that describes an exceptional (that is, error) condition that has occurred
in a piece of code.
❑ When an exceptional condition arises, an object representing that exception is created and thrown in
the method that caused the error.
❑ Any exception which is thrown, must be caught by an exception handler.
❑ If the programmer hasn't provided one, the exception will be caught by a catch-all exception
handler/default exception handler provided by the system.
❑ The default exception handler may terminate the application.
Exception Handling:
How Java Manage Exception Handling?

❑ Java has 5 keywords for exception handling:


❑ try - Program statements that you want to monitor for exceptions are contained within a try
block.
❑ catch - 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.
❑ finally - Any code that absolutely must be executed after a try block completes is put in a finally
block.
❑ throw - To manually throw an exception, use the keyword throw
❑ throws - Any exception that is thrown out of a method must be specified as such by a throws
clause
Syntax of try-catch
try {
// Code which might throw an exception
}
catch(Exception ex) {
// code to handle an exception
}
Exception declearation
Public void calculate () throws abcException{
//body
}
Public void calculate () throws abcException, otherExceptopn {
//body
}
Displaying a Description of an Exception
catch (ArithmeticException e) {
System.out.println("Exception: " + e);
}

Output:
Exception: java.lang.ArithmeticException: / by zero
Syntax of Multiple Catch Clauses
try {
// Code which might throw an exception
}
catch(FileNotFoundException x) {
// code to handle a FileNotFound exception
}
catch(IOException x) {
// code to handle any other I/O exceptions
}
catch(Exception x) {
// Code to catch any other type of exception
}
Syntax of Nested Try Statements
try {
try {
// Code which might throw an exception
}
catch(ArithmeticException ex1) {
// code to handle a ArithmeticException exception
}
}
catch(FileNotFoundException ex2) {
// code to handle a FileNotFound exception
}
Syntax of try-catch-finally
try {
// Code which might throw an exception
}
catch(IOException x) {
// code to handle any other I/O exceptions
}
catch(Exception x) {
// Code to catch any other type of exception
}
finally {
// This code is ALWAYS executed
}
Syntax of throw
❑ So far, we have only been catching exceptions that are thrown by the Java run-time system. However, it
is possible for our program to throw an exception explicitly, using the throw statement.
❑ The general form of throw is shown here:
Common Exceptions:-
❑ ArithmeticException:
❑ When we try to divide some value by 0, ArithmeticException occurs.
❑ For example: 42/0, it will throw an ArithmeticException.

Try {…….}
catch (ArithmeticException e) {
System.out.println("Exception: " + e);
}
❑ InputMismatchException:
❑ Occurs when an invalid input is given in a program.
❑ For example: it occurs when we give a character as input instead of an integer.
❑ NumberFormatException:
❑ Occurs when we try to convert a String to an integer or double, but the string does not contain
any numeric character.
❑ NullPointerException:
❑ Occurs when we try work (access/use/check) on a null value.
❑ ArrayIndexOutOfBoundException:
❑ Occurs when we try to access to an index position larger than the maximum index value of the
array index.
❑ For example, if the size of an array is 5 then, the maximum value of index is 4.
ArrayIndexOutOfBoundException will be thrown if we try to access an index position greater
than 4.

❑ IOException
❑ ClassnotFoundException
❑ NoClassDefFoundError
❑ IlligalStateExceptation
❑ SQLException
❑ FileNotFoundException

Syntax of throws
❑ If a method can cause an exception that it does not handle (we have seen it in throw example), it must
specify this behavior so that callers of the method can guard themselves against that exception.

❑ This is the general form of a method declaration that includes a throws clause:
Exception declearation:-
Public void calculate (int a, int b) {
If (a<0) {
Through new IllegalArgumentException(“Argument a can not be negative”);
}
if(b<0) {
Through new IllegalArgumentException(“Argument b can not be negative”);
}
}
Example of throw

// Fig. 15.3: UsingExceptions.java


2 // Demonstration of the try-catch-finally exception handling mechanism.
3 public class UsingExceptions {
4
5 public static void main( String args[] )
6 {
7 try {
8 throwException(); // call method throwException
9 }
10
11 // catch Exceptions thrown by method throwException
12 catch ( Exception exception ) {
13 System.err.println( "Exception handled in main" );
14 }
15
16 doesNotThrowException();
17 }
18
19 // demonstrate try/catch/finally
20 public static void throwException() throws Exception
21 {
22 // throw an exception and immediately catch it
23 try {
24 System.out.println( "Method throwException" );
25 throw new Exception(); // generate exception
26 }
27
28 // catch exception thrown in try block
29 catch ( Exception exception ) {
30 System.err.println(
31 "Exception handled in method throwException" );
32 throw exception; // rethrow for further processing [Rethrow Exception]
33
34 // any code here would not be reached
35 }
37 // this block executes regardless of what occurs in try/catch
38 The finally block executes, even though Exception thrown]
finally {[
39 System.err.println( "Finally executed in throwException" );
40 }
41
42 // any code here would not be reached
43
44 } // end method throwException
45
46 // demonstrate finally when no exception occurs
47 public static void doesNotThrowException()
48 {
49 // try block does not throw an exception
50 try {
51 System.out.println( "Method doesNotThrowException" );
52 }
53
54 // catch does not execute, because no exception thrown
55 catch ( Exception exception ) {
56 System.err.println( exception );
57 }
58
59 // this clause executes regardless of what occurs in try/catch
60 The finally block always executes]
finally { [
61 System.err.println(
62 "Finally executed in doesNotThrowException" );
63 }
64
65 System.out.println( "End of method doesNotThrowException" );
66
67 } // end method doesNotThrowException
68
69 } // end class UsingExceptions

Method throwException
Exception handled in method throwException
Finally executed in throwException
Exception handled in main
Method doesNotThrowException
Finally executed in doesNotThrowException
End of method doesNotThrowException

Advantages of Exception Handling:-


❑ Separating Error-Handling Code from "Regular" Code.
❑ Propagating Errors.
❑ Grouping and Differentiating Error Types.
Exception Types:-
Java Exception Types

Error vs Exception

Checked vs Unchecked
❑ Checked Exception (Compile Time Exception)
❑ A checked exception is an exception that occurs at the compile time. They are also called as
compile time exceptions. These exceptions cannot simply be ignored at the time of compilation.
❑ If your code invokes a method which is defined to throw checked exception, your code MUST
provide a catch handler.
❑ The compiler generates an error if the appropriate catch handler is not present.
❑ Checked exceptions are subclassed from Exception class.
❑ Unchecked Exception (Run Time Exception)
❑ An unchecked exception is an exception that occurs at the time of program execution. They are
also called as Runtime Exceptions.
❑ Runtime exceptions are ignored at the time of compilation.
❑ If an unchecked exception is not caught, it will go to the default catch-all handler for the
application.
❑ All Unchecked exceptions are subclassed from RuntimeException.
What is User Defined Exception?
❑ Although Java’s built-in exceptions handle most common errors, but sometimes it is necessary create
our own exception. These are user defined exception.
How to Define User Defined Exception?
❑ To define your own exception you must do the following:
❑ Create an exception class to hold the exception data.
❑ Your exception class must subclass "Exception" or another exception class
Note: to create unchecked exceptions, subclass the RuntimeException class.

❑ Minimally, your exception class should provide a constructor which takes the exception
description as its argument.
Example of User Defined Exception

Constructors and Exception Handling:-


Constructor cannot return a value to indicate an error

Throw exception if constructor causes error


For example, if invalid initialization value given to constructor and there is no sensible way to
correct this
Throw User Defined Exception
❑ To throw your own exceptions:
❑ If your exception is checked, any method which is going to throw the exception must define it
using the throws keyword
❑ When an exceptional condition occurs, create a new instance of the exception and throw it.

Example of How to throw User Defined Exception


Example of throws

printStackTrace, getStackTrace and getMessage:-


Throwable class
Method printStackTrace
Prints method call stack (helpful in debugging)
Method getStackTrace
Obtains stack-trace information
Method getMessage
Returns descriptive string

Uncaught exception – default exception handler – displays complete stack trace

1 // Fig. 15.5: UsingExceptions.java


2 // Demonstrating getMessage and printStackTrace from class Exception.
3 public class UsingExceptions {
4
5 public static void main( String args[] )
6 {
7 try {
8 method1(); // call method1 [Call method]
9 }
10
11 // catch Exceptions thrown from method1
12 catch ( Exception exception ) {
13 Print information generated by getMessage
System.err.println( exception.getMessage() + "\n" );[
and printStackTrace]
14 exception.printStackTrace();
15
16 // obtain the stack-trace information
17 StackTraceElement[] traceElements = exception.getStackTrace();
18
19 System.out.println( "\nStack trace from getStackTrace:" );
20 System.out.println( "Class\t\tFile\t\t\tLine\tMethod" );
21
22 // loop through traceElements to get exception description
23 Print StackTraceElements]
for ( int i = 0; i < traceElements.length; i++ ) {[
24 StackTraceElement currentElement = traceElements[ i ];
25 System.out.print( currentElement.getClassName() + "\t" );
26 System.out.print( currentElement.getFileName() + "\t" );
27 System.out.print( currentElement.getLineNumber() + "\t" );
28 System.out.print( currentElement.getMethodName() + "\n" );[Print StackTraceElements]
29
30 } // end for statement
31
32 } // end catch
33
34 } // end method main
35
36 // call method2; throw exceptions back to main
37 public static void method1() throws Exception[method1 declares a throw clause]
38 {
39 method2();
40 }
41
42 // call method3; throw exceptions back to method1
43 public static void method2() throws Exception[method2 declares a throw clause]
44 {
45 method3();
46 }
47
48 // throw Exception back to method2
49 public static void method3() throws Exception[method3 declares a throw clause]
50 {
51 throw new Exception( "Exception thrown in method3" );[Throw an Exception that propagates back to
main]
52 }
53
54 } // end class Using Exceptions
Exception thrown in method3

java.lang.Exception: Exception thrown in method3


at UsingExceptions.method3(UsingExceptions.java:51)
at UsingExceptions.method2(UsingExceptions.java:45)
at UsingExceptions.method1(UsingExceptions.java:39)
at UsingExceptions.main(UsingExceptions.java:8)

Stack trace from getStackTrace:


Class File Line Method
UsingExceptions UsingExceptions.java 51 method3
UsingExceptions UsingExceptions.java 45 method2
UsingExceptions UsingExceptions.java 39 method1
UsingExceptions UsingExceptions.java 8 main

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy