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

Exception Handling I

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

Exception Handling I

Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 21

JAVA Programming

Course Instructor: Dr. Suvojit Dhara


School of Computer Science
UPES Dehradun
TOPICs to be discussed

 Concept of Errors in Java

Exceptions in Java

Throwable class

Types of Exceptions

Different Exceptions in Java


Let’s START …!!!
Concept of Errors in Java
 Errors in Java indicate serious problems that typically stem from the environment in which
the application is running.
 Errors can be classified into two main categories: compile-time errors and runtime errors.
 Understanding these categories is crucial for effective debugging and ensuring robust code.

Compile-time Errors Runtime Errors


 When programmers make errors in  Program is syntactically correct, i.e.,
Syntax. compilation successful.
 Use methods which are not defined  Programs are running successfully for
anywhere. some input, but not all.
 Create objects of abstract classes  Very difficult to debug while writing
and many more… the program.
 Make the program unreliable and may
damage systems.
Compile-time Errors (Example)
Class Error {
Public static void main(String args[]) {
system.out.println("Can you find errors in me?")
} 1. ‘C’ is in capital in
}
“class” keyword.
class AnotherError { 2. ‘P’ is in capital in
public void insert() {
System.out.println("To insert a text");
“public” keyword.
return 10; 3. ‘s’ is in small letters
}
in “System” keyword.
abstract void delete() {
System.out.println("To delete a text"); 4. No semicolon(;) after
} the print statement.
}
5. return statement in
void function
6. body of an abstract
method
Some common Compile-time Errors

 Missing semicolons.
 Missing (or mismatch) of brackets in Classes and methods.
 Misspelling of identifiers or keywords.
 Missing double quotes in strings.
 Use of undeclared variables.
 Incomplete types in assignments / initialization.
 Bad references to objects.
and many more . . .
Runtime Errors (Example)
import java.util.Scanner;
class Error {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int a = sc.nextInt();
int b = sc.nextInt();

System.out.println("a divided by b : "+a/b);


}
}

Output:
(1) 2 1 a divided by b : 2
(2) 9 2 a divided by b : 4

(3) 1 0 Exception in thread "main" java.lang.ArithmeticException:


/ by zero
(4) 1.5 2.5 Exception in thread "main" java.util.InputMismatchException
Some common Runtime Errors

 A user has entered invalid input data.


 Dividing a number by zero.
 Accessing an element that is out of the bounds of an array.
 Trying to cast an instance of a class to one of its subclasses.
 Attempting use of a negative size of an array.
 Null object reference.
and many more . . .
Exceptions in Java
 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.

 The Exception object contains information about the exception, such as the name and
description of the exception and the state of the program when the exception occurred.

 Exceptions can be generated by the Java run-time system, or they can be manually
generated by your code. Exceptions thrown by Java relate to fundamental errors that violate
the rules of the Java language or the constraints of the Java execution environment.
Throwable Class
 All exception and error types are
subclasses of the class Throwable,
which is the base class of the
exception hierarchy.
 One branch is headed by Exception.
This class is used for exceptional
conditions that user programs should
catch.
 NullPointerException is an
example of such an exception.
 Another branch, Error is used by the
JVM to indicate errors having to do
with the run-time environment (JRE),
itself.
 StackOverflowError is an example
of such an error.
Common methods in Throwable
class ThrowableExample {
 String getMessage(): Returns the public static void main(String[] args) {
try {
detail message string of this throwable. int result = 10/0;
} catch (ArithmeticException e) {
System.out.println("Message: " +
 Throwable getCause(): Returns
the cause of this throwable or null if the e.getMessage());
System.out.println("Cause: " +
cause is nonexistent or unknown.
e.getCause());
System.out.println("Exception: "
 String toString(): Returns a + e.toString());
e.printStackTrace();
short description of this throwable. }
}
}
 void printStackTrace(): Prints Output:
the throwable and its backtrace to the Message: / by zero
Cause: null
standard error stream.
Exception: java.lang.ArithmeticException: / by zero
java.lang.ArithmeticException: / by zero
at Main.main(Main.java:4)
Types of Exception
 The two main types of exceptions are:
 Checked Exceptions (Compile-time Exceptions)
 Unchecked Exceptions (Runtime Exceptions)

Checked Exceptions: Unchecked Exceptions:


 Checked exceptions are exceptions that are  Unchecked exceptions are exceptions that are not
checked by the Java compiler at compile time. checked by the Java compiler at compile time.
 Programs are required to either catch (handle)  Programs are not required to catch or declare
checked exceptions using a try-catch block or unchecked exceptions. Instead, they are thrown
declare them using the throws. and discovered at runtime.
 Common examples of checked exceptions  Common examples of unchecked exceptions
include IOException, SQLException, and include ArrayIndexOutOfBoundsException,
ClassNotFoundException. These exceptions NullPointerException, ArithmeticException,
often relate to external factors, such as file etc. These exceptions often indicate
I/O, database access, and class loading. programm-ing errors or unexpected conditions.
Different Exceptions in Java
 Java Exceptions can be also categorized into two categories: built-in exceptions and user-
defined exceptions.

 Some common built-in exceptions in Java are:


 ArithmeticException
 IOException
 NumberFormatException
 ArrayIndexOutOfBoundsException
 StringIndexOutOfBoundsException
 NullPointerException
and many more…
ArithmeticException
 ArithmeticException is thrown when an exceptional condition has occurred in an arithmetic
operation.

class ArithmeticException_Example1 { class ArithmeticException_Example2 {


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

int a = 2; int max = Integer.MAX_VALUE;


int b = 0; int result = Math.addExact(max, 1);

System.out.println("a modulo b: " +


System.out.println("Result: " + result);
a%b);
}
Output:
} Output:
}
Exception in thread "main"
} Exception in thread "main"
java.lang.ArithmeticException: / by zero java.lang.ArithmeticException: integer overflow
at Main.main(Main.java:6) at
java.base/java.lang.Math.addExact(Math.java:825)
at Main.main(Main.java:4)
IOException
 IOException is raised when an input-output operation failed or interrupted in a Java
program.

import java.io.FileReader;
import java.io.IOException;

class IOException_Example {
public static void main(String[] args) {
//Attempt to read from a file that doesn't exist
FileReader reader = new FileReader("nonexistentfile.txt");

reader.close();
}
}
Output:
Error: unreported exception FileNotFoundException; must be caught or declared to be thrown
FileReader reader = new FileReader("nonexistentfile.txt");
^
Main.java:8: Error: unreported exception IOException; must be caught or declared to be thrown
reader.close();
^
NumberFormatException
 NumberFormatException is raised when a method could not convert a string into a numeric
format.

class NumberFormatException_Example {
public static void main(String[] args) {
int num = Integer.parseInt ("Student") ; //trying to assign a string
to an integer variable
System.out.println(num);
}
}

Output:
Exception in thread "main" java.lang.NumberFormatException: For input string: "Student"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:65)
at java.base/java.lang.Integer.parseInt(Integer.java:652)
at java.base/java.lang.Integer.parseInt(Integer.java:770)
at Main.main(Main.java:3)
ArrayIndexOutOfBoundsException
 ArrayIndexOutOfBoundsException 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.

class ArrayIndexOutOfBound_Example {
public static void main(String args[]) {
int a[] = new int[5];
a[6] = 9; //accessing 7th element in an array of size 5
}
}

Output:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: Index 6 out of bounds for
length 5
at Main.main(Main.java:4)
StringIndexOutOfBoundsException
 StringIndexOutOfBoundsException is thrown by String class methods to indicate that an
index is either negative or greater than the size of the string.

class StringIndexOutOfBound_Example {
public static void main(String args[]) {
String s = "This is like chipping "; //String length is 22
char ch = s.charAt(24); //accessing 25th element

System.out.println(ch);
}
}

Output:
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: 24
at java.base/java.lang.StringLatin1.charAt(StringLatin1.java:47)
at java.base/java.lang.String.charAt(String.java:693)
at Main.main(Main.java:4)
NullPointerException
 NullPointerException is thrown when referring to the members of a null object. Null
represents nothing.

class NullPointerException_Example {
public static void main(String args[]) {
String s = null; //null value
char ch = s.charAt(0); //accessing first element of the string

System.out.println(ch);
}
}

Output:
Exception in thread "main" java.lang.NullPointerException
at Main.main(Main.java:4)
Summary
Today, we learned about

• Concept of Errors in Java

• Concept of Exceptions in Java

• Throwable Class

• Types of Exceptions

• Some common exceptions (ArithmeticException, IOException, NumberFormatException,


ArrayIndexOutOfBoundsException, StringIndexOutOfBoundsException,
NullPointerException, etc.)

You might also like