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

Unit 8 Original (1)

The document provides an overview of error handling in Java, detailing types of errors such as syntax errors, runtime errors, and logical errors, along with their definitions and examples. It explains the concept of exceptions, including built-in and user-defined exceptions, and highlights the importance of exception handling in maintaining program flow and error reporting. Key built-in exceptions like ArithmeticException, NullPointerException, and FileNotFoundException are also discussed with illustrative code examples.

Uploaded by

richelpatel2712
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)
4 views

Unit 8 Original (1)

The document provides an overview of error handling in Java, detailing types of errors such as syntax errors, runtime errors, and logical errors, along with their definitions and examples. It explains the concept of exceptions, including built-in and user-defined exceptions, and highlights the importance of exception handling in maintaining program flow and error reporting. Key built-in exceptions like ArithmeticException, NullPointerException, and FileNotFoundException are also discussed with illustrative code examples.

Uploaded by

richelpatel2712
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/ 46

Object oriented programming with Java

Meenakshi Prajapati
Assistant Professor
Computer Science and Engineering
Contents
⮚ Errors
⮚ Types of Error
⮚ Exception and its types
⮚ Difference between Error and exception
⮚ tryCatch method
⮚ Difference between Final, Finally and Finalize
⮚ Difference between Throw and Throws
Unit 8

Exception Handling
What is an Error in Java?
What is an Error

⮚ In Java, an error is a subclass of Throwable that tells that something serious problem is existing and a reasonable Java application should not try to catch that error.

⮚ Generally, it has been noticed that most of the occurring errors are abnormal conditions and cannot be resolved by normal conditions.
Types of
Errors
Syntax error
⮚ A syntax error in Java is like a grammatical mistake in your code. It's a violation of the strict rules that Java uses to
understand your instructions.
⮚ Just like a misspelled word can confuse someone reading a sentence, a syntax error prevents the Java compiler (the
program that translates your code into machine code) from making sense of your program.

⮚ For example :Mismatched parentheses, Incorrect keyword


Missing semicolon:
int age = 25 // Missing semicolon here
System.out.println("Hello!");
Types of Syntax error
1.Missing Parentheses or Brackets: Forgetting to include closing parentheses ), square brackets ], or curly braces {} can lead to syntax
errors, especially in expressions, function calls, or data structures.

2.Missing Semicolons: In languages that use semicolons to terminate statements (e.g., C, Java, JavaScript), omitting a semicolon at the end
of a statement can result in a syntax error.

2.Mismatched Quotes: Forgetting to close quotation marks ' or " around strings can lead to syntax errors, as the interpreter/compiler will
interpret everything until the next matching quote as part of the string.

2.Incorrect Indentation: In languages like Python, incorrect indentation can cause syntax errors, especially within control structures like
loops, conditional statements, or function definitions.

2.Misspelled Keywords or Identifiers: Misspelling keywords, variable names, function names, or other identifiers can result in syntax
errors. The interpreter/compiler won’t recognize these misspelled names, leading to errors
Syntax error

⮚ Fixing syntax errors:


The good news is that syntax errors are usually easy to fix! Once you identify the error from the compiler message, you
can simply correct the mistake according to Java's grammar rules. Many development environments (IDEs) also help by
highlighting syntax errors as you type.
Example
Mismatched parentheses
if (age > 18) { // Missing closing parenthesis here
System.out.println("You are an adult");
}
Syntax error

Real world Syntax Error Problems:


1.Configuration Files: Syntax errors can occur in configuration files (e.g., XML, JSON, YAML) used by applications. For instance, a missing closing tag in
an XML file or a misplaced comma in a JSON file can lead to syntax errors.

1.Markup Languages: In markup languages like HTML or Markdown, syntax errors can occur due to missing or mismatched tags. For example, forgetting
to close a <div> tag or using incorrect indentation in Markdown can result in syntax errors.

1.SQL Queries: Syntax errors are common in SQL queries, especially when writing complex statements. Errors can occur due to missing commas, incorrect
table aliases, or improper placement of keywords like SELECT, FROM, WHERE, etc.

1.Regular Expressions: Writing regular expressions with incorrect syntax can lead to errors. Common mistakes include missing escape characters,
mismatched parentheses, or invalid quantifiers.

1.Command Line Syntax: Incorrect usage of command-line tools and utilities can result in syntax errors. For example, providing the wrong option or
argument format when executing commands can lead to errors.
Runtime
error
Runtime Errors:

• A runtime error in a program is an error that occurs while the program is running after being successfully compiled.

• Runtime errors are commonly called referred to as “bugs” and are often found during the debugging process before the
software is released.

• When runtime errors occur after a program has been distributed to the public, developers often release patches, or small
updates designed to fix the errors.

• While solving problems on online platforms, many run time errors can be faced, which are not clearly specified in the
message that comes with them. There are a variety of runtime errors that occur such as logical errors, Input/Output
errors, undefined object errors, division by zero errors, and many more.
Runtime
error
Types of Runtime Errors:
⮚ Arithmetic Exceptions:
These errors arise during mathematical operations. A classic example is the infamous java.lang.ArithmeticException caused by dividing
by zero.
Example:
int num1 = 10;
int num2 = 0;
int result = num1 / num2; // This will cause an ArithmeticException

⮚ ArrayIndexOutOfBoundsException:
This error pops up when you try to access an element in an array that's beyond its defined bounds. Imagine reaching for an item on a shelf
that doesn't exist.

Example:
int[] numbers = {1, 2, 3};
int element = numbers[4]; // This will cause an ArrayIndexOutOfBoundsException (trying to access index 4 in a 3-element array)
Runtime
error
Types of Runtime Errors:

⮚ NullPointerException: This error occurs when you attempt to use a variable that hasn't been assigned a value (it's null). It's like trying
to call a method on an empty object, like using a null cup to pour water.
Example:
String name = null;
System.out.println(name.toUpperCase()); // This will cause a NullPointerException (calling a method on a null object)

⮚ ClassCastException: This error happens when you try to cast an object to a type that it's not compatible with. It's like forcing a square
peg into a round hole – the object's type just doesn't match what you're expecting.
Example:
Object obj = new String("Hello");
Integer num = (Integer) obj; // This will cause a ClassCastException (casting a String to an Integer)

⮚ NumberFormatException: This error arises when you try to convert a string to a number format that it's not valid in. It's like trying to
interpret a word as a number – it just doesn't make mathematical sense.
Example:
String numberString = "abc";
int number = Integer.parseInt(numberString); // This will cause a NumberFormatException (trying to parse a non-numeric string)
Runtime
errorof a runtime error in Java, specifically a NullPointerException
Example

Explanation
1.We declare a String variable named name but don't assign it any value. This means it remains null.

2. The line System.out.println(name.toUpperCase()); tries to call the toUpperCase() method on the name variable.

3. Since name is null, attempting to use its method results in a NullPointerException. This error occurs because you're trying to call a
method on an object that doesn't exist (it's null).
Runtime
error
⮚ There are two ways to fix this error:
Logical error
⮚Logical Errors in Java

Logical errors, also known as semantic errors, are flaws in a program's code that cause it to produce incorrect
results or behave unexpectedly, even though it compiles and runs without crashing.

These errors can be particularly frustrating because the Java compiler or runtime environment (JVM) won't
explicitly point them out.

They stem from flaws in the programmer's logic or understanding of the problem being solved.
Types of Logical error
• Incorrect Operator Precedence: Java follows a specific order of operations when evaluating expressions. Misusing this order can
lead to unexpected results.
Example: int result = x * y + z; // This might not be what you intended
• Correction: Use parentheses to enforce the desired order, e.g., int result = (x * y) + z;

• Conditional Statement Errors: Faulty logic in if, else if, and switch statements can lead the program down the wrong path.
• Example: if (age >= 18) { // Might miss out on 18-year-olds
• Correction: Use if (age > 17) to include 18-year-olds.

• Off-by-One Errors: These occur when loops or calculations iterate one more or less time than intended.
• Example: for (int i = 0; i < 10; i++) { // Prints numbers 0-9, not 1-10
• Correction: Use i < 10 to print up to 9 (inclusive).
Logical error
• Floating-Point Precision Issues: Floating-point numbers can introduce slight inaccuracies due to their internal representation. Be cautious about comparing
them using exact equality (==).
• Example: if (value == 0.1) { ... } // Might not work as expected
• Correction: Use a comparison with a small tolerance, e.g., if (Math.abs(value - 0.1) < 0.001) { ... }

• Integer Division: Dividing integers results in another integer, discarding any remainder. Use type casting or floating-point division for exact results.
• Example: int average = total / count; // Might lose precision if count is not 1
• Correction: Use floating-point division, e.g., double average = (double)total / count;

• Unintended Variable Scope: Variables declared within a loop or block might not be accessible outside of that scope.
• Example: for (int i = 0; i < 10; i++) { int sum = 0; ... } // sum is not accessible outside the loop
• Correction: Declare sum before the loop if needed outside.

• Array Index Out of Bounds: Accessing elements outside the valid range of an array leads to runtime errors.
• Example: int[] numbers = {1, 2, 3}; int last = numbers[numbers.length]; // ArrayIndexOutOfBoundsException
• Correction: Use numbers[numbers.length - 1] to access the last element.
Example of Logical error
Scenario:
An e-commerce website offers a discount of 10% on orders above $100. The programmer implements the
following code to calculate the discounted price:
Example of Logical error

Logical Error:

The intended behavior is to apply a 10% discount if the order total is above $100. However, the code
uses the > operator in the if condition. This means the discount will be applied only if the order total is strictly greater than
$100 (i.e., $100.01 or higher). Orders exactly equal to $100 will not receive the discount.

Impact:

Customers with an order total of exactly $100 will pay the full price, even though they should have received
a discount. This can lead to customer dissatisfaction and lost revenue for the store.
Example of Logical error
⮚ Correction:
To fix the error, change the > operator to >= in the if condition:
Exception
⮚ What are Java Exceptions?
In Java, Exception is an unwanted or unexpected event, which occurs during the execution of a program, i.e. at run
time, that disrupts the normal flow of the program’s instructions. Exceptions can be caught and handled by the program.
When an exception occurs within a method, it creates an object. This object is called the exception object. It contains
information about the exception, such as the name and description of the exception and the state of the program when the
exception occurred.

⮚ Major reasons why an exception Occurs


• Invalid user input
• Device failure
• Loss of network connection
• Physical limitations (out-of-disk memory)
• Code errors
• Opening an unavailable file
Types of Exceptions
Exception
⮚ Exceptions can be categorized in two ways:
1.Built-in Exceptions
1. Checked Exception
2. Unchecked Exception
2.User-Defined Exceptions

⮚ 1. Built-in Exceptions
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error
situations.

• Checked Exceptions: Checked exceptions are called compile-time exceptions because these exceptions are checked at compile-
time by the compiler.

• Unchecked Exceptions: The unchecked exceptions are just opposite to the checked exceptions. The compiler will not check these
exceptions at compile time. In simple words, if a program throws an unchecked exception, and even if we didn’t handle or declare
it, the program would not give a compilation error.
Exception
⮚ User-Defined Exceptions:
Sometimes, the built-in exceptions in Java are not able to describe a certain situation. In such cases, users can also
create exceptions, which are called ‘user-defined Exceptions’.

⮚ Advantages of Exception Handling in Java


1.Provision to Complete Program Execution
2.Easy Identification of Program Code and Error-Handling Code
3.Propagation of Errors
4.Meaningful Error Reporting
5.Identifying Error Types
Exception
Built-in Exceptions
Built-in exceptions are the exceptions that are available in Java libraries. These exceptions are suitable to explain certain error
situations. Below is the list of important built-in exceptions in Java.

ArithmeticException: It is thrown when an exceptional condition has occurred in an arithmetic operation.

ArrayIndexOutOfBoundsException: It is thrown to indicate that an array has been accessed with an illegal index. The index
is either negative or greater than or equal to the size of the array.

ClassNotFoundException: This Exception is raised when we try to access a class whose definition is not found

FileNotFoundException: This Exception is raised when a file is not accessible or does not open.

IOException: It is thrown when an input-output operation failed or interrupted

InterruptedException: It is thrown when a thread is waiting, sleeping, or doing some processing, and it is interrupted.
Continue…
NoSuchFieldException: It is thrown when a class does not contain the field (or variable) specified

NoSuchMethodException: It is thrown when accessing a method that is not found.

NullPointerException: This exception is raised when referring to the members of a null object. Null represents nothing

NumberFormatException: This exception is raised when a method could not convert a string into a numeric format.

RuntimeException: This represents an exception that occurs during runtime.

StringIndexOutOfBoundsException: It is thrown by String class methods to indicate that an index is either negative or greater than the size of
the string

IllegalArgumentException : This exception will throw the error or error statement when the method receives an argument which is not
accurately fit to the given relation or condition. It comes under the unchecked exception.

IllegalStateException : This exception will throw an error or error message when the method is not accessed for the particular operation in the
application. It comes under the unchecked exception.
Examples of Built-in Exception
A. Arithmetic exception
class ArithmeticException_Demo Output
{ Can't divide a number by 0
public static void main(String args[])
{
try {
int a = 30, b = 0;
int c = a/b; // cannot divide by zero
System.out.println ("Result = " + c);
}
catch(ArithmeticException e) {
System.out.println ("Can't divide a number by 0");
}
}
}
B. NullPointer Exception
class NullPointer_Demo
{
public static void main(String args[])
{
try {
String a = null; //null value
System.out.println(a.charAt(0));
} catch(NullPointerException e) {

System.out.println("NullPointerException..");
}
}
}
Output
NullPointerException..
C. StringIndexOutOfBound Exception
class StringIndexOutOfBound_Demo
{
Output
public static void main(String args[])
StringIndexOutOfBoundsException
{
try {
String a = "This is like chipping "; // length is 22
char c = a.charAt(24); // accessing 25th element
System.out.println(c);
}
catch(StringIndexOutOfBoundsException e) {
System.out.println("StringIndexOutOfBoundsException");
}
}
}
D. FileNotFound Exception
import java.io.File;
import java.io.FileNotFoundException;
Output:
import java.io.FileReader;
class File_notFound_Demo {
File does not exist
public static void main(String args[]) {
try {

// Following file does not exist


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

FileReader fr = new FileReader(file);


} catch (FileNotFoundException e) {
System.out.println("File does not exist");
}
}
}
E. NumberFormat Exception
class NumberFormat_Demo
{ Output
public static void main(String args[]) Number format
{ exception
try {
// "akki" is not a number
int num = Integer.parseInt ("akki") ;

System.out.println(num);
} catch(NumberFormatException e) {
System.out.println("Number format exception");
}
}
}
F. ArrayIndexOutOfBounds Exception
class ArrayIndexOutOfBound_Demo
{
public static void main(String args[]) Output
{ Array Index is Out Of
try{ Bounds
int a[] = new int[5];
a[6] = 9; // accessing 7th element in an array of
// size 5
}
catch(ArrayIndexOutOfBoundsException e){
System.out.println ("Array Index is Out Of Bounds");
}
}
}
G. IO Exception
class IOException_Demo {

public static void main(String[] args) Output:


{
// Create a new scanner with the specified String Hello Geek!
// Object Exception Output: null
Scanner scan = new Scanner("Hello Geek!");

System.out.println("" + scan.nextLine());

// Check if there is an IO exception


System.out.println("Exception Output: "
+ scan.ioException());

scan.close();
}
H. NoSuchMethod Exception
public class NoSuchElementException_Demo {

public static void main(String[] args) { Output


Set exampleleSet = new HashSet(); This throws a NoSuchElementException as there are
no elements in Set and HashTable and we are
Hashtable exampleTable = new Hashtable(); trying to access elements

exampleleSet.iterator().next();
//accessing Set

exampleTable.elements().nextElement();
//accessing Hashtable
}
}
I. IllegalArgumentException:
import java.io.*;

class IllegalArgumentExceptionDemo { Output :


public static void print(int a)
{ Exception in thread "main"
if(a>=18){ java.lang.IllegalArgumentException: Not
System.out.println("Eligible for Voting"); Eligible for Voting
} at IllegalArgumentExceptionDemo
else{ .print(File.java:13)
throw new IllegalArgumentException("Not Eligible for Voting"); at )
}
}
public static void main(String[] args) {
IllegalArgumentExceptionDemo.print(14);
}
}
J. IllegalStateException:
import java.io.*; Output :

class IllegalStateExceptionDemo { Exception in thread "main"


public static void print(int a,int b) { java.lang.IllegalStateException:
System.out.println("Addition of Positive Integers :"+(a+b)); Either one or two numbers are
} not Positive Integer
public static void main(String[] args) { at IllegalStateExceptionDemo
int n1=7; .main(File.java:20)
int n2=-3;
if(n1>=0 && n2>=0){
IllegalStateExceptionDemo .print(n1,n2);
}
else {
throw new IllegalStateException("Either one or two numbers are not Positive Integer");
}
}}
k. ClassNotFound Exception :
public class ClassNotFoundException_Demo
{
public static void main(String[] args) {
try{ Output
Class.forName("Class1"); // Class1 is not defined java.lang.ClassNotFoundException:
} Class1
catch(ClassNotFoundException e){ Class Not Found...
System.out.println(e);
System.out.println("Class Not Found...");
}
}
}
User Defined Exception
class MyException extends Exception { catch (MyException ex) {
public MyException(String s) System.out.println("Caught");
{
// Call constructor of parent Exception // Print the message from MyException object
super(s); System.out.println(ex.getMessage());
} }
} }
// A Class that uses above MyException }
public class Main {
// Driver Program
public static void main(String args[])
{ Output
try { Caught
// Throw an object of user defined exception Shown my Exceptions
throw new MyException(“Shown my Exceptions");
}
Errors vs Exceptions
Try and Catch
⮚ In Java exception is an “unwanted or unexpected event”, that occurs during the execution of the program. When an exception occurs, the
execution of the program gets terminated. To avoid these termination conditions we can use try catch block in Java.
⮚ Why Does an Exception occur?
An exception can occur due to several reasons like a Network connection problem, Bad input provided by a user, Opening a non-existing file
in your program, etc.

⮚ Blocks and Keywords Used For Exception Handling


1. try in Java
The try block contains a set of statements where an exception can occur.
Continue…
2. catch in Java
The catch block is used to handle the uncertain condition of a try block. A try block is always followed by a catch block, which handles the exception that
occurs in the associated try block.

3. throw in Java
The throw keyword is used to transfer control from the try block to the catch block.

4. throws in Java
The throws keyword is used for exception handling without try & catch block. It specifies the exceptions that a method can throw to the caller and does not
handle itself.

5. finally in Java
It is executed after the catch block. We use it to put some common code (to be executed irrespective of whether an exception has occurred or not ) when there
are multiple catch blocks.
Difference between Final, Finally and Finalize
Difference Between Throw and Throws
References
[1] https://www.geeksforgeeks.org/exceptions-in-java/?ref=header_search

[2] https://images.app.goo.gl/aWDptkcFsi7U9Ltd8

[3] https://www.shiksha.com/online-courses/articles/difference-between-errors-and-exceptions-in-java

[4] https://www.geeksforgeeks.org/exceptions-in-java/?ref=header_search

[5] https://www.geeksforgeeks.org/flow-control-in-try-catch-finally-in-java/?ref=lbp

[6] https://www.geeksforgeeks.org/try-catch-throw-and-throws-in-java/?ref=lbp

[7] https://stackify.com/specify-handle-exceptions-java/

[8] https://www.programiz.com/java-programming/exception-handling

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