6 Exception Handlingi Oabstract Cl 250201 171638
6 Exception Handlingi Oabstract Cl 250201 171638
1. TRY
2. CATCH
3. THROW
4. THROWS
5. FINALLY
EXAMPLE OF EXCEPTION:
class Main {
try {
int divideByZero = 5 / 0;
} catch (ArithmeticException e) {
} }
}
EXCEPTION AND ERROR
Exceptions are events that occurs in the code. A programmer can handle such conditions
and take necessary corrective actions
Errors indicate that something severe enough has gone wrong, the application should
crash rather than try to handle the error.
1. Missing Semicolon
2. Wrong Spelling of keywords and
identifiers
3. Missing brackets of class and
methods
4. Missing double quotes in the string
5. Use of undeclared Variables.
6. Use of = instead of ==
7. Incompatible types in assignment
statements
8. Illegal references to the object
RUN-TIME ERROR
➔ Sometimes the program is free
from the compile time errors and
creates a .class file
➔ It is basically the logic errors,that
get caused due to the wrong logic.
1. Accessing the array element which
is out of the index.
2. In an expression,divided by zero.
3. Trying to store a value into an
array of incompatible type.
4. Passing the parameters that is not
in valid in range
5. Converting invalid string to
numbers
6. Trying to illegally change the state
of thread.
TRY-CATCH BLOCK: SYNTAX:
Try block try
Exception
Exception objects gets {
causing created over
statement here //Exception gets generated here
}
Catch block
catch (ExceptionType name)
Exception {
Exception
handling
Handler
statement
//Exception is handled here
}
Example of Try-Catch Block:
https://www.youtube.com/watch?list=PLHuIqV4DwPicArdMjI2YI5Hu5c2TnMgvV&time_continu
e=110&v=VIbZRUjh2d0&feature=emb_logo
Uncaught Exception:
If there exists some code in the source program which may cause an exception and if the
programmer does not handle this exception than java run time system raised the exception.
statement;
The try block within a try block is known
try
as nested try block in java.
{
have to be nested. }
catch(Exception e)
}
SYNTAX:
Multiple Catch Block try
{
➔ As I mentioned above, a single try
//Exception gets generated here
block can have any number of catch
blocks. }
}
Using Throws SYNTAX:
[i]
According to the Java Compiler - "we must
//Declaring one checked exception
either catch checked exceptions by
using throws keyword
providing appropriate try-catch block or we
should declare them, using throws." public void method1() throws
IOException //method signature{}
[ii]
Hence, when a method doesn't want to
method_name(parameter_list)throws
catch/handle one or more checked exceptions
exception_list
by providing an appropriate try-catch block
within, it must use throws keyword in its {}
method signature to declare that it does not
handle but only throws such checked
exceptions.
Using throw
➔ you may use the throw keyword when you explicitly want to
throw an exception. The keyword throw is followed by an object
of the exception class that you want to throw. Using throw
keyword, an exception can be explicitly thrown from within the
two places in a Java program -
● try-block or,
● catch-block.
Throw in Try Block Throw in Catch Block
To throw an exception out of try block, To throw an exception out of catch block,
keyword throw is followed by creating a keyword throw is followed by object
new object of exception class that we reference of the exception class that was
wish to throw. For example - caught by catch block. For example -
try catch(IOException io)
{ {
// An object of IOException exception throw io; // An existing exception
class is created using "new" keyword. class object referenced by "io" of type
"IOException", is thrown.
throw new IOException();
}
}
Finally Clause
Class Declaration
Following is the declaration for java.lang.Throwable class −
public class Throwable
extends Object
implements Serializable
Re-throwing Exception:
➔ An exception can be rethrown in a catch block. This action will cause the exception to
be passed to the calling method. If the rethrow operation occurs in the main method
then the exception is passed to the JVM and displayed on the console. The purpose of
the rethrow operation is to get the attention of the outside world that an exception has
occurred and at the same time perform any contingency logic (such as logging) in the
catch block.
OUTPUT:
Chained Exception
➔ Chained Exceptions allows to relate one exception with another exception, i.e one
exception describes cause of another exception.
➔ For example, consider a situation division operation a/b in which a b is 0 which
throws an ArithmeticException because of an attempt to divide by zero but the actual
cause of exception was an I/O error (bcz wrong input value to variable b)which
caused the divisor to be zero. The method will throw only ArithmeticException to the
caller. So the caller would not come to know about the actual cause of exception.
Chained Exception is used in such type of situations.
CONT...
The throwable class supports chained exception using the following methods:
Constructors
1. Throwable(Throwable cause) - the cause is the current exception.
2. Throwable(String msg, Throwable cause) - msg is the exception message, the
cause is the current exception.
Methods
1. getCause - returns actual cause.
2. initCause(Throwable cause) - sets the cause for calling an exception.
Defining Custom Exception Classes
➔ Java provides us facility to create our own exceptions which are basically derived
classes of Exception. For example MyException in below code extends the Exception
class.
➔ We pass the string to the constructor of the super class- Exception which is obtained
https://www.youtube.com/watch?v=ohpCMpderow
https://www.youtube.com/watch?v=NsctooZANVk
I/O
File Class and its Input and Output
➔ The java.io package contains nearly every class you might ever need to perform input and output
(I/O) in Java. All these streams represent an input source and an output destination
➔ The File class contains several methods for working with the path name, deleting and renaming
files, creating new directories, listing the contents of a directory, and determining several
common attributes of files and directories.
➔ A pathname, whether abstract or in string form can be either absolute or relative. The parent of
an abstract pathname may be obtained by invoking the getParent() method of this class.
➔ First of all, we should create the File class object by passing the filename or directory name to it.
A file system may implement restrictions to certain operations on the actual file-system object,
such as reading, writing, and executing. These restrictions are collectively known as access
permissions.
How to create a File Object?
➔ A File object is created by passing in a String that represents the name of a file, or a
➔ defines an abstract file name for the geeks file in directory /usr/local/bin. This is an
➔ A relative path is a path which doesn’t start with the root element of the file system. It
is simply the path needed in order to locate the file from within the current directory
of your program. It is not complete and needs to be combined with the current
directory path in order to reach the requested file.
➔ In order to construct a rigid and platform independent program, it is a common
convention to use a relative path when locating a file inside your program.
resources on Internet, telling us the address of the resource, how to communicate with it and retrieve something from
it.
➔ The Java URLConnection class represents a communication link between the URL
and the application. This class can be used to read and write data to the specified
resource referred by the URL.
➔ How to get the object of URLConnection class
➔ The openConnection() method of URL class returns the object of URLConnection
class. Syntax:
public URLConnection openConnection()throws IOException{}
output:
ABSTRACT
CLASSES
Abstract Classes:
➔ A class which is declared as abstract is known as an abstract class. It can have abstract and
non-abstract methods. It needs to be extended and its method implemented. It cannot be
instantiated.
Points to Remember:
A method which is declared as abstract and does not have implementation is known as an
abstract method.
Example of abstract method
abstract void printStatus();
Abstact Class v/s Concrete Class
Interfaces
Interfaces
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.
There are mainly three reasons to use interface. They are given below.
interface <interface_name>{
// by default.
}
syntax:
acess_modifier interface name_of_interface
return_type method_name1(parameter1,parameter2,......,parametern);
return_type method_name2(parameter1,parameter2,......,parametern);
}
Extending Interfaces
An interface can extend another interface in the same way that a class can extend another
class. The extends keyword is used to extend an interface, and the child interface inherits
the methods of the parent interface.
Syntax:
//body of interface
}
Example:
Interface A
Int val=10;
Interface B extends A
Void print_val();
}
Interface A
Int val=10;
Interface B extends A
Void print_val();
…...
}
Comparable Interface
➔ Java Comparable interface is used to order the objects of the user-defined class. This
interface is found in java.lang package and contains only one method named
compareTo(Object). It provides a single sorting sequence only, i.e., you can sort the
elements on the basis of single data member only. For example, it may be rollno,
name, age or anything else.
➔ If we use Arrays and List objects then these objects can be sorted automatically by
Collection.sort method which is basically implements comparable interfaces.
compareTo(Object obj) method
public int compareTo(Object obj): It is used to compare the current object with the
specified object. It returns
● positive integer, if the current object is greater than the specified object.
● negative integer, if the current object is less than the specified object.
● zero, if the current object is equal to the specified object.
Cloneable Interface
➔ The object cloning is a way to create exact copy of an object. The clone() method of
Object class is used to clone an object.
➔ The java.lang.Cloneable interface must be implemented by the class whose object
clone we want to create. If we don't implement Cloneable interface, clone() method
generates CloneNotSupportedException.
What if we don’t implement Cloneable interface?
Does clone object and original object point to the same location in memory
The answer is no. The clone object has its own space in the memory where it copies the
content of the original object. That’s why when we change the content of original object
after cloning, the changes does not reflect in the clone object. Lets see this with the help of
an example.
VIDEO LINKS FOR
I/O,ABSTRACT
CLASS AND
INTERFACES
Example of URL Class, How to Parse URL in Java
https://www.youtube.com/watch?v=DuFyhu5_GPs
Cloneable Interface
https://www.youtube.com/watch?v=b2uFL4BFDYg