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

Java Concepts

Concepts of Java
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
16 views

Java Concepts

Concepts of Java
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 19

Exception Handling

Compile-time errors: These are syntactical errors found in the code,


due to which a program fails to compile. For example, 'forgetting a
semicolon at the end of a Java statement, or writing a statement
without proper syntax will result in compile-lime error.
Ex: System.out.print(“hello”) //missing semicolon
This is will be detected by the Java compiler.
Run-time errors:These errors represent inefficiency of the· computer
system to execute a particular statement. For example, insufficient
memory to store something or inability of the microprocessor to execute
some statement come under run-time errors.
Run-time errors are not detected by java compiler, they are detected by
jvm at runtime only.
For example , if the program expects to read in a number, but instead
the user enters a string, this causes data-type errors to occur in the
program.
Another example of runtime errors is division by zero. This happens
when the divisor is zero for integer divisions. For instance, the following
program would cause a runtime error:

public class JavaDemo {


public static void main(String[] args) {

System.out.println(10/0);

}}

Output:

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


at com.javaguides.JavaDemo.main(JavaDemo.java:24)

Logical Error: A logic error is when your program compiles and


executes, but does the wrong thing or returns an incorrect result or no
output when it should be returning an output. These errors are detected
neither by compiler nor by JVM.The programmer is solely responsible
for them.
The Exception Handling in Java is one of the powerful mechanism to
handle the exceptions so that normal flow of the application can be
maintained.
Exceptions Types:
Checked exceptions − A checked exception is an exception that is
checked (notified) by the compiler at compilation-time, these are also
called as compile time exceptions. These exceptions cannot simply be
ignored, the programmer should take care of (handle) these exceptions.
If these exceptions are not handled you will get compilation error. For
example, SQLException, IOException, ClassNotFoundException etc.
Checked exceptions are recovrable.
For example, if you use FileReader class in your program to read data
from a file, if the specified file is doesn't exist, then a
FileNotFoundException occurs, and the compiler prompts the
programmer to handle the exception.
import java.io.File;
import java.io.FileReader;

class FilenotFound_Demo {

public static void main(String args[]) {


File file = new File("E://file.txt");
FileReader fr = new FileReader(file);
}
}

output

C:\>javac FilenotFound_Demo.java
FilenotFound_Demo.java:8: error: unreported exception
FileNotFoundException; must be caught or declared to be thrown
FileReader fr = new FileReader(file);
^
1 error

Unchecked exceptions − An unchecked exception is an exception


checked by JVM at runtime . These are also called as Runtime
Exceptions.Unchecked exceptions are considered as unrecoverable and
the programmer cannot do any thing when they occurFor example,
ArithmeticException, NullPointerException,
ArrayIndexOutOfBoundsException etc. Runtime exceptions are ignored
at the time of compilation.
For example, if you have declared an array of size 5 in your program,
and trying to call the 6th element of the array then an
ArrayIndexOutOfBoundsExceptionexception occurs.

Ex:
class Unchecked_Demo {

public static void main(String args[]) {


int num[] = {1, 2, 3, 4};
System.out.println(num[5]);
}

Output
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
5
at Exceptions.Unchecked_Demo.main(Unchecked_Demo.java:8)

Common Scenarios of Java Exceptions


There are given some scenarios where unchecked exceptions may occur.
They are as follows:

1) A scenario where ArithmeticException occurs


If we divide any number by zero, there occurs an ArithmeticException.
1. Int a=50/0;//ArithmeticException

2) A scenario where NullPointerException occurs


If we have a null value in any variable, performing any operation on the
variable throws a NullPointerException.
1. String s=null;
2. System.out.println(s.length());//NullPointerException

3) A scenario where NumberFormatException occurs


The wrong formatting of any value may occur NumberFormatException.
Suppose I have a string variable that has characters, converting this
variable into digit will occur NumberFormatException.
1. String s="abc";
2. int i=Integer.parseInt(s);//NumberFormatException

4) A scenario where ArrayIndexOutOfBoundsException occurs


If you are inserting any value in the wrong index, it would result in
ArrayIndexOutOfBoundsException as shown below:
1. int a[]=new int[5];
2. a[10]=50; //ArrayIndexOutOfBoundsException

HIERARCHY OF EXCEPTION CLASS:

Errors V/s Exceptions In Java


• Error : An Error “indicates serious problems that a reasonable
application should not try to catch.”
Both Errors and Exceptions are the subclasses of
java.lang.Throwable class. Errors are the conditions which cannot
get recovered by any handling techniques. It surely cause
termination of the program abnormally. Errors belong to
unchecked type and mostly occur at runtime. Some of the
examples of errors are Out of memory error or a System crash
error.
Exception :An exception is an abnormal condition or a problem
that arises during the execution of a program. When an Exception
occurs the normal flow of the program is disrupted and the
program/Application terminates abnormally, which is not
recommended, therefore, these exceptions are to be handled.
EXCEPTION HANDLING:
TRY BLOCK: The programmer should observe the statements in his
program where there- may be a possibility of exceptions. Such
statements should be written inside a try block. A try block looks like as
follows:
try{
statements;
}
The try statement allows you to define a block of code to be tested for
errors while it is being executed.When JVM understands that there is an
exception in try block , it stores the exception details in an exception
stack and then jumps into a catch block.
A try block must be followed by catch blocks or finally block or both.
CATCH BLOCK: The programmer should write the Catch block where
he should display the exception details to the user. This helps the user to
understand that there is some error in the program. The programmer
should also display a message regarding what can be done to avoid this
error. Catch block looks like as follows:
catch(Exception e) {
// Block of code to handle errors
}

The catch statement allows you to define a block of code to be executed,


if an error occurs in the try block. Here e refers exception details in
exception stack, by using print statement we can print exception details.
Consider the following example:
This will generate an error, because myNumbers[10] does not exist.
class MyClass {
public static void main(String[ ] args) {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]); // error!
System.out.println("hello");
}}
The output will be something like this:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException:
10
at MyClass.main(MyClass.java:4)
If an error occurs, we can use try...catch to catch the error and execute
some code to handle it:

Example
class MyClass {
public static void main(String[ ] args) {
try {
int[] myNumbers = {1, 2, 3};
System.out.println(myNumbers[10]);
} catch (Exception e) {
System.out.println("Something went wrong.");
}
System.out.println("hello");
}}

The output will be: Something went wrong. hello

Java finally block:

Java finally block is a block that is used to execute important code


such as closing connection, stream etc.
Java finally block is always executed whether exception is handled or
not.
Java finally block follows try or catch block.Finally block in java can be
used to put "cleanup" code such as closing a file, closing connection etc.
Let's see the different cases where java finally block can be used.

For each try block there can be zero or more catch blocks, but only one
finally block.

Case 1
Let's see the java finally example where exception doesn't occur.
class TestFinallyBlock{
public static void main(String args[]){
try{
int data=25/5;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
output: 5
finally block is always executed
rest of the code..

Case 2
Let's see the java finally example where exception occurs and not
handled.
class Test{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data);
}
catch(NullPointerException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code...");
}
}
output: finally block is always executed
Exception in thread "main" java.lang.ArithmeticException: / by zero
at Test.main(9.java:4)

Case 3
Let's see the java finally example where exception occurs and
handled
class TestFinallyBlock2{
public static void main(String args[]){
try{
int data=25/0;
System.out.println(data); }
catch(ArithmeticException e){System.out.println(e);}
finally{System.out.println("finally block is always executed");}
System.out.println("rest of the code..."); } } }
output: java.lang.ArithmeticException: / by zero
finally block is always executed
rest of the code...
IMP POINTS:1. a single try block can have any number of catch
blocks.
2. A generic catch block can handle all the exceptions. Whether it is
ArrayIndexOutOfBoundsException or ArithmeticException or
NullPointerException or any other type of exception, this handles all of
them.
3. If no exception occurs in try block then the catch blocks are
completely ignored.
4. Corresponding catch blocks execute for that specific type of
exception:
catch(ArithmeticException e) is a catch block that can hanlde
ArithmeticException
catch(NullPointerException e) is a catch block that can handle
NullPointerException
Multiple catch blocks:
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
// System.out.println(a[10]);
System.out.println("First print statement in try block");
}
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning: ArrayIndexOutOfBoundsException");
}
catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
}}
Output:

Warning:ArithmeticException
Out of try-catch block...

2.class Example{
public static void main(String args[]){
try{
int arr[]=new int[7];
arr[10]=10/5;
System.out.println("Last Statement of try block");
}
catch(ArithmeticException e){
System.out.println("You should not divide a number by zero");
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println("Accessing array elements outside of the
limit");
}
catch(Exception e){
System.out.println("Some Other Exception");
}
System.out.println("Out of the try-catch block");
}
}

Output:
Accessing array elements outside of the limit
Out of the try-catch block

In this case, the second catch block got executed because the code
throws ArrayIndexOutOfBoundsException. We are trying to access the
11th element of array in above program but the array size is only 7.
throw keyword in java with example:
An exception is unwanted problem that disturbs normal execution and
there is a need to indicate that something goes wrong to jvm we need
to raise the exception explicitly
The Java throw keyword cerates an exception object and handover it to
jvm spcially in the case of userdefined exceptions because jvm doesnt
know anything about user defined exceptions.
Simply this keyword is used to handover our cerated exception object
to jvm manually to indicate something goes wrong.
We can throw either checked or uncheked exception in java by throw
keyword. The throw keyword is mainly used to throw custom exception.
Ex: class test
{ public static void main(String args[])
{ System.out.println(10/0);
}}
here main method is responsible for to create arirhmetic exception
object and handover to jvm. There is no code to handle that exception
by jvm so at runtime we will get exception like
Exception in thread "main" java.lang.ArithmeticException: / by zero
at test.main(9.java:3)
here main method is responsible to create the exception object and
handover to jvm. All this happends internally.
Now we will see how to create our own exception object explicitly and
handover to jvm manually.

Syntax of throw keyword:


throw new exception_class("error message");

for ex: throw new ArithmeticException("sorry");

here new ArithmeticException("sorry"); creates our own exception


object and throw keyword will handover that exception to jvm
explicitly

ex: class test

{ public static void main(String args[])

{ throw new ArithmeticException("sorry");


}}

and there is no code to handle the exception for jvm. So finally we will
get runtime exception as above

Exception in thread "main" java.lang.ArithmeticException: sorry

at test.main(9.java:3)

all this happends manually by using throw keyword.

Case study1:

class test {

public static void main(String args[])

{ System.out.print(10/0);

System.out.print("hello"); }}

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


zero

at test.main(9.java:7)

here compiler doesnt know about ArithmeticException at compile time


and we will get runtime exception at runtime.

class test {

public static void main(String args[])

{ throw new ArithmeticException("sorry");

System.out.print("hello"); }}

output : 9.java:9: error: unreachable statement

System.out.print("hello");

^ 1 error

here at compile time only compiler knows about ArithmeticException so


we will get compile time error like unreachable statement
case study 2:

class test {

public static void main(String args[])

{ throw new test(); }}

output: 9.java:5: error: incompatible types: test cannot be converted to


Throwable

throw new test();

^ 1 error

here throw keyword can raise only exception and errors which are sub
classes of throwable. Test() is not subclass of throwable class so we
will get incompatible type error at compile time.

class test extends RuntimeException

{ public static void main(String args[])

{ throw new test(); }}

here test is a compatible type of throwable class( test class is sub


class of runtime exception class, runtime exception is sub class of
exception class, exception class is sub class of throwable class) so we
wont get any compile time error but we will get runtime exception
because there is no code to handle test exception for jvm like

Exception in thread "main" test

at test.main(9.java:5)

User defined exception: or (custom exception)


Custom Exceptions are user-defined exceptions. These are written by
programmers specifically for there application use cases.
Sometimes to meet our program requirements we have to define our
own exceptions and we have to raise those exceptions based on our
requirement.
the exceptions cerated by programmer explicitly to meet requirements
are called user defined exceptions.
To create a checked custom exception, it must extend Exception or its
child classes.
To create Unchecked custom exception extends RuntimeException or its
child classes.
All Exceptions are a child of Throwable.
Ex: withdraw(double amount)
{ if(amount>balance)
{ throw new InSuffieientBalance();
}}
to create userdefined exception
first we need to define our exception by extending runtime exception
class and to provide some information about our exception we have to
define a parameterized constructor like
class tooyoungexception extends runtimeexception
{ tooyoungexception(string msg)
{ super(msg); } }
here super(msg); passing the msg to parent class.
class toooldexception extends runtimeexception
{ tooyoungexception(string msg)
{ super(msg); } }
here tooyoungexception and toooldexception are the two user difined
or customized exceptions.
Example:
class tooyoungException extends RuntimeException
{
tooyoungException(String msg)
{ super(msg);
}
}
class toooldException extends RuntimeException
{
toooldException(String msg)
{ super(msg);
}
}
class test
{
public static void main(String args[])
{
int a=Integer.parseInt(args[0]);
if(a>60)
{
throw new tooyoungException("please wait somemore time you will
get definetly best match");
}
else if(a<18)
{
throw new toooldException("your age already crossed marriage no
chance of getting marriage");
}
else
System.out.print("thanks for u r registration");
}}
output: java test 99
Exception in thread "main" tooyoungException: please wait somemore
time you will get definetly best match
at test.main(w.java:21)
>java test 14
Exception in thread "main" toooldException: your age already crossed
marriage no chance of getting marriage
at test.main(w.java:25)
>java test 33
thanks for u r registration.
JVM have the information about built in exceptions but it doesnot
having information about user defined exceptions.and throw keyword is
used to throw Our defined exception to jvm explicitly.
Here tootoungException and toooldException are subclass of runtime
exception class, runtime exception class is subclass of exception class,
exception class is sub class of throwabl class.
Whenever we throwing tootoungException there is no catch block to
handle it, so it will cause abnormal termination. In the case of an
abnormal termination is the responsible for printing exception
information to console.
The default exception handler use the printStackTrace() method which
is available in Throwable class to print exception information on
console.
To make exception description avaliable to Throwable class we use the
statement super(msg); now the printStackTrace() method of
Throwable class print the exception description on console.
If we comment this // super(msg); then we will get the output
>java test 99
Exception in thread "main" tooyoungException
at test.main(w.java:21)
here tooyoungException and toooldException are inherited from
Runtimeexception class so these are unchecked exceptions. for these
unchecked exceptions no need of try and catch blocks so the compiler
has no objection about these at compile time.
If we inherite the tooyoungException and toooldException from
exception class then they will become checked exceptions. To handle
the checked exceptions we need try catch block. If there is no try catch
block in code to handle these checked exceptions the compiler raise
compile time error.
Throw keyword is highly recommended for unchecked exceptions
because it is used to indicate something goes wrong to jvm . So there
is no need of exception handled code.
Throws clause in java checked exception (compile time) force you to
handle them, if you don’t handle them then the program will not
compile.
On the other hand unchecked exception (Runtime) doesn’t get checked
during compilation. Throws keyword is used for handling checked
exceptions .
ex; import java.io.*;
class test
{
public static void main(String args[])
{
PrintWriter pw=new PrintWriter("abc.txt");
pw.println("hello");
}}
output: javac e.java
e.java:6: error: unreported exception FileNotFoundException; must be
caught or declared to be thrown
PrintWriter pw=new PrintWriter("abc.txt");
^
1 error
here one checked exception is raised. And There are 2 ways to handle
checked exceptions
1. by using try catch block
import java.io.*;
class test {
public static void main(String args[])
{
try
{
PrintWriter pw=new PrintWriter("abc.txt");
pw.println("hello");
}
catch(FileNotFoundException e)
{ }}}
output: no exception and successfully compiled

2. by using throws keyword


purpose of throws keyword is used to delegate responsibility of
exception handling to the caller(jvm) . Now the caller is responsible to
handle this exception.
import java.io.*;
class test
{
public static void main(String args[])throws FileNotFoundException
{
PrintWriter pw=new PrintWriter("abc.txt");
pw.println("hello");
}
}
output: no exception
among these two ways only (try catch block) first way is recommended
becauses if we use throws keyword there may be abnormal termination.
This keyword required only for checked exceptions.
And it is required only to convince compiler and its usage does not
prevent abnormal termination of program.
throws keyword is also used to delegate responsibility of
exception handling to another method
ex:
import java.io.*;
class test
{
public static void main(String args[]) throws FileNotFoundException
{
dostuff();
}
public static void dostuff() throws FileNotFoundException
{
domorestuff();
}
public static void domorestuff() throws FileNotFoundException
{
PrintWriter pw=new PrintWriter("abc.txt");
pw.println("hello");
}}
compliled successfully. In every method instead of throws we can also
use try catch to handle exception.

Difference between throw and throws in java


1. Throws clause is used to declare an exception, which means it works
similar to the try-catch block. On the other hand throw keyword is used
to throw an exception explicitly.
2. If we see syntax wise than throw is followed by an instance of
Exception class and throws is followed by exception class names.
For example:
throw new ArithmeticException("Arithmetic Exception");

3. Throw keyword is used in the method body to throw an exception,


while throws is used in method signature to declare the exceptions that
can occur in the statements present in the method.
For example:
Throw:
...void myMethod() {
try {
//throwing arithmetic exception using throw
throw new ArithmeticException("Something went wrong!!");
}
catch (Exception exp) {
System.out.println("Error: "+exp.getMessage());
}}
Throws:
//Declaring arithmetic exception using throws
void sample() throws ArithmeticException{
//Statements
}
4. You can throw one exception at a time but you can handle multiple
exceptions by declaring them using throws keyword.
For example:
Throw:
void myMethod() {
//Throwing single exception using throw
throw new ArithmeticException("An integer should not be divided by
zero!!");
}
..Throws:

//Declaring multiple exceptions using throws


void myMethod() throws ArithmeticException, NullPointerException{
//Statements where exception might occur
}

You might also like