[go: up one dir, main page]

0% found this document useful (0 votes)
9 views38 pages

Managing Errors and Exceptions

The document provides an overview of error and exception management in programming, specifically focusing on Java. It categorizes errors into compile-time and runtime errors, explains exceptions and their types, and discusses the importance of exception handling. Key concepts such as try, catch, throw, and finally blocks are introduced as mechanisms to manage exceptions effectively.

Uploaded by

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

Managing Errors and Exceptions

The document provides an overview of error and exception management in programming, specifically focusing on Java. It categorizes errors into compile-time and runtime errors, explains exceptions and their types, and discusses the importance of exception handling. Key concepts such as try, catch, throw, and finally blocks are introduced as mechanisms to manage exceptions effectively.

Uploaded by

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

Managing Errors

and Exceptions
What You Will Learn

Use to
try, watch for
throw, indicate exceptions
handle
catch

How to process exceptions and failures.

2
Syntax Errors, Runtime Errors, and
Logic Errors

Syntax errors arise because the rules of


the language have not been followed.
They are detected by the compiler.
Runtime errors occur while the program
is running if the environment detects an
operation that is impossible to carry out.
Logic errors occur when a program
doesn't perform the way it was intended
to.
3
Introduction
 Rarely does the program run successful at its
very first attempt. It is common to make the
mistakes while developing as well as typing a
program.
 A mistake might lead to an error causing to
program to produce unexpected results.
 Errors are the wrongs that can make a program
go wrong.
 An error may produce an incorrect result or may
terminate the execution of the program
abruptly or even may cause the system to
crash.
Types of Errors
 Errors may be broadly
classified into two types.
 Compile time Errors
 Run Time Errors
Compile Time Errors
 Compile time error means Java
compiler identify the syntax error at
the time of compilation.
 And without successfully compilation,
compiler does not create .class file.
 That means we have to compile the
program which should be error free and
then compiler creates .class file of the
program and then we can run the
program.
Compile Time Errors
 /* This Program Contains an Error

class Error1
{
public static void main(String args[])
{
System.out.println(“Hello Java”)
}
}

Error1.java :7: ‘ : ’ expected


System.out.println(“Hello java”)
^
1 error
Compile Time Errors
 Most compile-time errors are due to typing mistakes.
 The most common problems are :
 Missing semicolon
 Missing (or mismatch of ) brackets in classes and
methods.
 Misspelling of identifiers and keywords
 Missing double quotes in strings.
 Use of undeclared variables
 Incompatible types in assignments /initialization
 Bad reference to objects
 Use of = in place of ==operator
 And so on
Run Time Errors
 Several time program may compile
successfully and compiler creates the .class
file of the program.
 but when the time of running the program, it
shows the error and that type of error called
run time error.
 Such program may produce wrong results
due to wrong logic or may terminate due to
errors such as stack overflow.
Run Time Errors
 Most Common run time errors are :
 Dividing an integer by Zero
 Accessing an element that is out of the bounds of
an array.
 Trying to store a value into an array of an
incompatible class or type.
 Trying to cast an instance of class to one of its
subclasses.
 Passing a parameter that is not a valid range or
value for a method.
 Trying to illegally change the state of thread.
 Attempting to use a negative size for an array.
 Converting invalid strings to number.
Run Time Errors
class errors2
{
public static void main(String args[])
{
int a=10,b=5,c=5;
int x=a/(b-c);
System.out.println(“X= “ +x)
int y=a/(b+c);
System.out.println(“Y= “ +y)
}
} Java.lang.ArithmeticException: / by
zero
What is an exception?
 Dictionary Meaning: Exception is an
abnormal condition.
 An Exception is a condition that is caused by
a run-time error in the program.
 When java interpreter encounters an error such
as dividing an integer by zero, it creates an
exception object and throws it.(i.e. informs us
that error has occurred.)
What is an exception?
 An Exception can be anything which
interrupts the normal flow of the
program.
 When an exception occurs program
processing gets terminated and doesn’t
continue further.
 In such cases we get a system
generated error message.
 The good thing about exceptions is that
they can be handled.
When an exception can
occur?
 Exception can occur at runtime (known as
runtime exceptions) as well as at compile-
time (known Compile-time exceptions).
 Reasons for Exceptions
There can be several reasons for an
exception.
 For example, following situations can cause
an exception -
 Opening a non-existing file,
 Network connection problem,
 Operands being manipulated are out of
prescribed ranges,
Why to handle exception?
 If an exception is raised, which has not been handled
by programmer then program execution can get
terminated and system prints a non user friendly
error message.
 Ex:-Take a look at the below system generated
exception
Exception in thread "main"
java.lang.ArithmeticException: / by zero at
ExceptionDemo.main(ExceptionDemo.java:5)
 For a novice user the above message won’t be easy to
understand.
 In order to let them know that what went wrong we
use exception handling in java program.
 We handle such conditions and then prints a user
Types of exceptions
 There are two types of exceptions
1) Checked exceptions
2) Unchecked exceptions
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.
 If these exceptions are not handled/declared
in the program, it will give compilation error.
 Examples of Checked Exceptions :-
ClassNotFoundException
IllegalAccessException
NoSuchFieldException
EOFException etc.
Unchecked Exceptions
 Runtime Exceptions are also known as Unchecked
Exceptions as the compiler do not check whether
the programmer has handled them or not but it’s the
duty of the programmer to handle these exceptions
and provide a safe exit.
 These exceptions need not be included in any
method’s throws list because compiler does not
check to see if a method handles or throws these
exceptions.
 Examples of Unchecked Exceptions:-
ArithmeticException
ArrayIndexOutOfBoundsException
NullPointerException
NegativeArraySizeException etc.
Common java Exceptions
Exception Meaning
ArithmeticException Arithmetic error, such as divide-by-zero
ArrayIndexOutOfBoundsExcept Array index is out-of-bounds
ion
ArrayStoreException Assigning an element of an incompatible
type
ClassCastException Invalid cast
EnumConstantNotPresentExce Attempt made to use undefined
ption enumeration value
IllegalArgumentException Illegal argument used to invoke a method
IllegalMonitorStateException Illegal monitor operation, such as waiting on
an unlocked thread
IllegalStateException Environment or application is in incorrect
state
IllegalThreadStateException Requested operation not compatible with
current thread state
Exception Meaning
NullPointerException Invalid use of a null reference
NumberFormatException Invalid conversion of a string to a numeric
format
SecurityException Attempt to violate security
StringIndexOutOfBoundsExcep Attempt to index outside the bounds of a
tion string
TypeNotPresentException Type not fount
UnsupportedOperationExcepti An unsupported operation was
on
ClassNotFoundException encountered
Class not found
CloneNotSupportedException Attempt to clone an object that does not
implement the Cloneable interface
IllegalAccessException Access to a class is denied
InstantiationException Attempt to create an object of an abstract
class or interface
InterruptedException One thread has been interrupted by
another thread
NoSuchFieldException A requested field does not exist
NoSuchMethodException A requested method does not exist
Exception hierarchy
Exception Handling in Java
 Java allows Exception handling
mechanism to handle various
exceptional conditions.
 When an exceptional condition occurs,
an exception is thrown.
 For continuing the program execution,
the user should try to catch the
exception object thrown by the error
condition and then display an
appropriate message for taking
corrective actions.
Exception Handling in
This Java
mechanism consists of :
1. Find the problem (Hit the Exception)
2. Inform that an error has occurred
(Throw the Exception)
3. Receive the error Information
(Catch the Exception)
4. Take corrective actions
(Handle the Exception)
Exception Handling in
Java
In Java Exception handling is
managed by 5 keywords:
try
catch
throw
throws
finally
Exception Handling in Java
Syntax of Exception Handling Code
 The basic concept of exception handling are
throwing an exception and catching it.

try & catch try Block

Statement that
causes Exception

Catch Block

Statement that
handles the Exception
What is Try Block?
 The try block contains a block of
program statements within which an
exception might occur.
 A try block must followed by a Catch
block or Finally block or both.

Syntax of try block


try{
//statements that may cause an
exception
}
What is Catch Block?
 A catch block must be associated with a try block.
 The corresponding catch block executes if an
exception of a particular type occurs within the
try block. 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
}
class errors2{
public static void main(String args[]) {
int a=10,b=5,c=5;
try{
int x=a/(b-c);
}
catch(ArithmeticException e) {

System.out.println(“Division by zero”);
}
int y=a/(b+c);
System.out.println(“Y= “ +y)
}
}
public static void main(String args[])
{
int num1, num2;
try { num1 = 0;
Error: Don't divide a number by zero
num2 = 62 / num1;
I'm out of try-catch block in Java.
System.out.println("Try block
message");
}
catch (ArithmeticException e)
{
System.out.println("Error: Don't divide a number by
zero");
}
System.out.println("I'm out of try-catch block in
Java.");
}
Multiple catch Statements
try {
//Protected code
}
catch(ExceptionType1 e1) {
//Catch block
}
catch(ExceptionType2 e2) {
//Catch block
}
catch(ExceptionType3 e3) {
//Catch block
}
Sequence of Events
Preceding step

try block

statement

unmatched catch

matching catch

unmatched catch

next step
class Example2{
public static void main(String args[]){
try{
int a[]=new int[7];
a[4]=30/0;
System.out.println("First print statement in try
block"); }
catch(ArithmeticException e){
System.out.println("Warning: ArithmeticException"); }

catch(ArrayIndexOutOfBoundsException e){
System.out.println("Warning:ArrayIndexOutOfBoundsExcepti
on"); }

catch(Exception e){
System.out.println("Warning: Some Other exception");
}
System.out.println("Out of try-catch block...");
Multiple catch Statements
 A try block can have any number of catch
blocks.
 A catch block that is written for catching the
class Exception can catch all other
Syntax:
exceptions.
catch(Exception e)
{
//This catch block catches all the exceptions
}

 If multiple catch blocks are present in a program


then the above mentioned catch block should be
placed at the last as per the exception handling
best practices.
Nested try catch:

 The try catch blocks can be nested. One


try-catch block can be present in the
another try’s body. This is called Nesting
of try catch blocks.
 Each time a try block does not have a catch
handler for a particular exception, the stack
is unwound and the next try block’s catch
(i.e., parent try block’s catch) handlers are
inspected for a match.
 If no catch block matches, then the
java run-time system will
handle the exception.
 Syntax of Nested try Catch
//Main try block
try
{ statement 1;
//try-catch block inside another try block
try {
statement 3;}
catch(Exception e1) {
//Exception Message }
}
catch(Exception e2) //Catch of Main(parent) try
block
{ //Exception Message }
What is Finally Block
 A finally statement must be associated
with a try statement.
 It identifies a block of statements that
needs to be executed regardless of
whether or not an exception
occurs within the try block.
 After all other try-catch processing is
complete, the code inside the finally
block executes.
 It will run regardless of whether an
exception was thrown and handled by
Try-catch-finally
 In normal execution the finally block is executed
after try block. When any exception occurs first the
catch block is executed and then finally block is
executed.
Try Try
{ {
……. ……
} }
Finally catch(…)
{ {
……… }
} Finally
{
}
Sequence of Events for finally
clause
Preceding step

try block

statement

unmatched catch

matching catch

unmatched catch

finally

next step

You might also like