JAVA EXCEPTION HANDLING
N.V.Raja Sekhar Reddy
www.technolamp.co.in
Want more interesting...
Watch and Like us @ https://www.facebook.com/Technolamp.co.in
subscribe videos @ http://www.youtube.com/user/nvrajasekhar
what is exception?
what is exception handling?
When occur Exception in a program?
Why we use exception handling macanisum?
explain try, catch, finally keywords.
try,catch and finally-Rules.
Types of Exception.
example of Some java Pre-defined /Built-in exception class.
User-defined Eceptions
Exception in java?
Java - Exceptions. An exception (or exceptional event) is 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.
JAVA EXCEPTION HANDLING
N.V.Raja Sekhar Reddy
www.technolamp.co.in
Want more interesting...
Watch and Like us @ https://www.facebook.com/Technolamp.co.in
subscribe videos @ http://www.youtube.com/user/nvrajasekhar
what is exception?
what is exception handling?
When occur Exception in a program?
Why we use exception handling macanisum?
explain try, catch, finally keywords.
try,catch and finally-Rules.
Types of Exception.
example of Some java Pre-defined /Built-in exception class.
User-defined Eceptions
Exception in java?
Java - Exceptions. An exception (or exceptional event) is 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.
unit 4 msbte syallbus for sem 4 2024-2025AKSHAYBHABAD5
The Intel 8086 microprocessor, designed by Intel in the late 1970s, is an 8-bit/16-bit microprocessor and the first member of the x86 family of microprocessors1. Here’s a brief overview of its internal architecture:
Complex Instruction Set Computer (CISC) Architecture: The 8086 microprocessor is based on a CISC architecture, which supports a wide range of instructions, many of which can perform multiple operations in a single instruction1.
Bus Interface Unit (BIU): The BIU is responsible for fetching instructions from memory and decoding them, while also managing data transfer between the microprocessor and memory or I/O devices1.
Execution Unit (EU): The EU executes the instructions1.
Memory Segmentation: The 8086 microprocessor has a segmented memory architecture, which means that memory is divided into segments that are addressed using both a segment register and an offset1.
Registers: The 8086 microprocessor has a rich set of registers, including general-purpose registers, segment registers, and special registers
In this chapter we will discuss exceptions in the object-oriented programming and in Java in particular. We will learn how to handle exceptions using the try-catch construct, how to pass them to the calling methods and how to throw standard or our own exceptions using the throw construct.
Synthetic Fiber Construction in lab .pptxPavel ( NSTU)
Synthetic fiber production is a fascinating and complex field that blends chemistry, engineering, and environmental science. By understanding these aspects, students can gain a comprehensive view of synthetic fiber production, its impact on society and the environment, and the potential for future innovations. Synthetic fibers play a crucial role in modern society, impacting various aspects of daily life, industry, and the environment. ynthetic fibers are integral to modern life, offering a range of benefits from cost-effectiveness and versatility to innovative applications and performance characteristics. While they pose environmental challenges, ongoing research and development aim to create more sustainable and eco-friendly alternatives. Understanding the importance of synthetic fibers helps in appreciating their role in the economy, industry, and daily life, while also emphasizing the need for sustainable practices and innovation.
The French Revolution, which began in 1789, was a period of radical social and political upheaval in France. It marked the decline of absolute monarchies, the rise of secular and democratic republics, and the eventual rise of Napoleon Bonaparte. This revolutionary period is crucial in understanding the transition from feudalism to modernity in Europe.
For more information, visit-www.vavaclasses.com
Embracing GenAI - A Strategic ImperativePeter Windle
Artificial Intelligence (AI) technologies such as Generative AI, Image Generators and Large Language Models have had a dramatic impact on teaching, learning and assessment over the past 18 months. The most immediate threat AI posed was to Academic Integrity with Higher Education Institutes (HEIs) focusing their efforts on combating the use of GenAI in assessment. Guidelines were developed for staff and students, policies put in place too. Innovative educators have forged paths in the use of Generative AI for teaching, learning and assessments leading to pockets of transformation springing up across HEIs, often with little or no top-down guidance, support or direction.
This Gasta posits a strategic approach to integrating AI into HEIs to prepare staff, students and the curriculum for an evolving world and workplace. We will highlight the advantages of working with these technologies beyond the realm of teaching, learning and assessment by considering prompt engineering skills, industry impact, curriculum changes, and the need for staff upskilling. In contrast, not engaging strategically with Generative AI poses risks, including falling behind peers, missed opportunities and failing to ensure our graduates remain employable. The rapid evolution of AI technologies necessitates a proactive and strategic approach if we are to remain relevant.
Francesca Gottschalk - How can education support child empowerment.pptxEduSkills OECD
Francesca Gottschalk from the OECD’s Centre for Educational Research and Innovation presents at the Ask an Expert Webinar: How can education support child empowerment?
Model Attribute Check Company Auto PropertyCeline George
In Odoo, the multi-company feature allows you to manage multiple companies within a single Odoo database instance. Each company can have its own configurations while still sharing common resources such as products, customers, and suppliers.
2024.06.01 Introducing a competency framework for languag learning materials ...Sandy Millin
http://sandymillin.wordpress.com/iateflwebinar2024
Published classroom materials form the basis of syllabuses, drive teacher professional development, and have a potentially huge influence on learners, teachers and education systems. All teachers also create their own materials, whether a few sentences on a blackboard, a highly-structured fully-realised online course, or anything in between. Despite this, the knowledge and skills needed to create effective language learning materials are rarely part of teacher training, and are mostly learnt by trial and error.
Knowledge and skills frameworks, generally called competency frameworks, for ELT teachers, trainers and managers have existed for a few years now. However, until I created one for my MA dissertation, there wasn’t one drawing together what we need to know and do to be able to effectively produce language learning materials.
This webinar will introduce you to my framework, highlighting the key competencies I identified from my research. It will also show how anybody involved in language teaching (any language, not just English!), teacher training, managing schools or developing language learning materials can benefit from using the framework.
Instructions for Submissions thorugh G- Classroom.pptxJheel Barad
This presentation provides a briefing on how to upload submissions and documents in Google Classroom. It was prepared as part of an orientation for new Sainik School in-service teacher trainees. As a training officer, my goal is to ensure that you are comfortable and proficient with this essential tool for managing assignments and fostering student engagement.
How to Make a Field invisible in Odoo 17Celine George
It is possible to hide or invisible some fields in odoo. Commonly using “invisible” attribute in the field definition to invisible the fields. This slide will show how to make a field invisible in odoo 17.
The Roman Empire A Historical Colossus.pdfkaushalkr1407
The Roman Empire, a vast and enduring power, stands as one of history's most remarkable civilizations, leaving an indelible imprint on the world. It emerged from the Roman Republic, transitioning into an imperial powerhouse under the leadership of Augustus Caesar in 27 BCE. This transformation marked the beginning of an era defined by unprecedented territorial expansion, architectural marvels, and profound cultural influence.
The empire's roots lie in the city of Rome, founded, according to legend, by Romulus in 753 BCE. Over centuries, Rome evolved from a small settlement to a formidable republic, characterized by a complex political system with elected officials and checks on power. However, internal strife, class conflicts, and military ambitions paved the way for the end of the Republic. Julius Caesar’s dictatorship and subsequent assassination in 44 BCE created a power vacuum, leading to a civil war. Octavian, later Augustus, emerged victorious, heralding the Roman Empire’s birth.
Under Augustus, the empire experienced the Pax Romana, a 200-year period of relative peace and stability. Augustus reformed the military, established efficient administrative systems, and initiated grand construction projects. The empire's borders expanded, encompassing territories from Britain to Egypt and from Spain to the Euphrates. Roman legions, renowned for their discipline and engineering prowess, secured and maintained these vast territories, building roads, fortifications, and cities that facilitated control and integration.
The Roman Empire’s society was hierarchical, with a rigid class system. At the top were the patricians, wealthy elites who held significant political power. Below them were the plebeians, free citizens with limited political influence, and the vast numbers of slaves who formed the backbone of the economy. The family unit was central, governed by the paterfamilias, the male head who held absolute authority.
Culturally, the Romans were eclectic, absorbing and adapting elements from the civilizations they encountered, particularly the Greeks. Roman art, literature, and philosophy reflected this synthesis, creating a rich cultural tapestry. Latin, the Roman language, became the lingua franca of the Western world, influencing numerous modern languages.
Roman architecture and engineering achievements were monumental. They perfected the arch, vault, and dome, constructing enduring structures like the Colosseum, Pantheon, and aqueducts. These engineering marvels not only showcased Roman ingenuity but also served practical purposes, from public entertainment to water supply.
2. Objectives
After you have read and studied this
chapter, you should be able to
Improve the reliability of code by
incorporating exception-handling.
Implement the try-catch blocks for catching
and handling exceptions.
Write methods that propagate exceptions.
Distinguish the checked and unchecked, or
runtime, exceptions.
3. Definition
An exception represents an error
condition that can occur during the
normal course of program execution.
Examples
Division by zero
Trying to open an input file that does not
exist
An array index that goes out of bounds
4. Java’s Mechanism of Exception
Handling
When an exception occurs, an object of a
particular exception class can be created
and thrown.
The exception-handling routine can then be
executed to catch & handle the exception
object; we say the thrown exception is caught.
The normal sequence of flow is terminated if
the exception object is thrown.
5. Exception thrown
Scanner scan = new Scanner(System.in);
int num = 0;
System.out.print(“Enter an integer>”);
num = scan.nextInt();
System.out.println(“The number you entered is “ +num);
Enter an integer> three
Exception in thread "main" java.util.InputMismatchException
at java.util.Scanner.throwFor(Unknown Source)
at java.util.Scanner.next(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at java.util.Scanner.nextInt(Unknown Source)
at ExceptionTest.main(ExceptionTest.java:11)
Error message for invalid input
6. Java’s Mechanism of
Exception Handling
(continued) Java provides a number of exception
classes to effectively handle certain
common exceptions such as division by
zero, invalid input, and file not found
Example:
When a Scanner object is used to input
data into a program, any invalid input
errors are handled using the class
InputMismatchException
When a division by zero exception occurs,
the program creates an object of the
class ArithmeticException
7. Exception Types
All types of thrown exception objects are
instances of the Throwable class or its
subclasses.
Serious errors are represented by instances of the
Error class or its subclasses.
Exceptional cases that common applications
should handle are represented by instances of the
Exception class or its subclasses.
9. Catching an Exception
To catch an exception:
•Put code that might throw an exception inside a try{} block.
•Put code that handles the exception inside a catch{} block.
Use try{} and catch{} block
try {
// statements, some of which might
// throw an exception
}
catch ( SomeExceptionType ex ) {
// statements to handle this
// type of exception
}
10. Catching an Exception
Scanner scan = new Scanner(System.in);
int num = 0;
try {
System.out.print(“Enter an integer>”);
num = scan.nextInt();
} catch (InputMismatchException e){
System.out.println(“Invalid input! Please enter
digits only");
}
System.out.println(“The number you entered is “ +num);
try
catch
12. Getting Information
There are two methods we can call to
get information about the thrown
exception:
getMessage
printStackTracetry {
. . .
} catch (NumberFormatException e){
System.out.println(e.getMessage());
System.out.println(e.printStackTrace());
}
13. Multiple catch Blocks
A single try-catch statement can include multiple catch
blocks, one for each type of exception.
try {
. . .
age = Integer.parseInt(inputStr);
. . .
val = cal.get(id);
. . .
} catch (NumberFormatException e){
. . .
} catch (ArrayIndexOutOfBoundsException e){
. . .
}
14. Multiple catch Control Flow
-Only one catch{} block gets control (the first block that matches the type of the exception ).
-If no catch{} block matches the exception, none is picked (just as if there were no try{} block.)
15. Multiple catch Control Flow
•The most specific exception types should appear first in the structure,
followed by the more general exception types.
A child class should appear before any of its ancestors. If class A is not
an ancestor or descendant of class B, then it doesn't matter which appears first.
Eg. the following is wrong:
try {
...
} catch (Exception ex ) {
. . .
} catch (ArithmeticException ex ) {
. . .
}
16. Multiple catch Control Flow
Question: Is this ok?:
try {
...
} catch (NumberFormatException ex ) {
. . .
} catch (ArithmeticException ex ) {
. . .
}
17. The finally Block
There are situations where we need to take certain actions regardless
of whether an exception is thrown or not.
We place statements that must be executed regardless of exceptions
in the finally block.
try {
// statements, some of which might
// throw an exception
} catch ( SomeExceptionType ex ) {
// statements to handle this
// type of exception
} catch ( AnotherExceptionType ex ) {
// statements to handle this
// type of exception
} finally {
// statements which will execute no matter
// how the try block was exited.
}
19. Propagating Exceptions
Instead of catching a thrown exception by using the
try-catch statement, we can propagate the thrown
exception back to the caller of our method.
The method header includes the reserved word
throws.
public int getAge( ) throws NumberFormatException {
. . .
int age = Integer.parseInt(inputStr);
. . .
return age;
}
20. Throwing Exceptions
We can write a method that throws an exception
directly, i.e., this method is the origin of the exception.
Use the throw reserved to create a new instance of the
Exception or its subclasses.
The method header includes the reserved word
throws.
public void doWork(int num) throws Exception {
. . .
if (num != val) throw new Exception("Invalid val");
. . .
}
21. Exception Thrower
When a method may throw an
exception, either directly or indirectly, we
call the method an exception thrower.
Every exception thrower must be one of
two types:
catcher.
propagator.
22. Types of Exception Throwers
An exception catcher is an exception
thrower that includes a matching catch
block for the thrown exception.
An exception propagator does not
contain a matching catch block.
A method may be a catcher of one
exception and a propagator of another.
24. Checked vs. Unchecked Exception
There are two types of exceptions:
Checked.
Unchecked.
A checked exception is an exception
that is checked at compile time, so it
must be handled.
An unchecked exception is not checked
at compile time, so no need to handle
(optional).
unchecked exception include Error and
RuntimeException and their subclasses.
checked exception include Exception
25. Different Handling Rules
When calling a method that can throw
checked exceptions
use the try-catch statement and place the
call in the try block, or
modify the method header to include the
appropriate throws clause.
When calling a method that can throw
runtime exceptions, it is optional to use
the try-catch statement or modify the
method header to include a throws
clause.
We can increase our programs’ reliability and robustness if we catch the exceptions ourselves using error recovery routines we develop.
One way to do this is to wrap the statements that may throw an exception with the try-catch control statement.
Consider the given example. What would happen if the user enters a value such as the text 'ten' instead of 10? The parseInt method cannot convert such an input to an internal numerical format. This type of error is called an exception, and it will result in displaying an error message such as the one shown here. We say the parseInt method has thrown a NumberFormatException.
The classes shown here are some of the more common classes in the Throwable class hierarchy. We will be seeing most of the Exception and its subclasses shown here in the later modules.
This example shows a way to handle a thrown exception in our code, instead of letting the system handle it, as in the previous example. If any statement inside the try block throws an exception, then the statements in the matching catch block are executed. And the program continues the execution from the statement that follows this try-catch statement.
This example shows a way to handle a thrown exception in our code, instead of letting the system handle it, as in the previous example. If any statement inside the try block throws an exception, then the statements in the matching catch block are executed. And the program continues the execution from the statement that follows this try-catch statement.
This illustrates how the control flows when there is an exception and when there is no exception.
In the case when no statements in the try block throw an exception, then the catch block is skipped and execution continues with the next statement following the try-catch statement.
If any one of the statements throws an exception, the statements in the catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
In the previous example, we simply displayed a fixed error message. We can get display a more generic error message by using the getMessage or printStrackTrace methods. We will experiment with these methods in the lab.
In this example, we see two statements in the try block that can potentially throw exceptions. The parseInt method throws a NumberFormatException while the get method throws an ArrayIndexOutOfBoundsException when the argument id is outside the range of valid values.
Here's how the control flows when there are multiple catch blocks.
In the case when no statements in the try block throw an exception, then all catch blocks are skipped and execution continues with the next statement following the try-catch statement.
If any one of the statements throws an exception, the statements in the matching catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
Here's how the control flows when there are multiple catch blocks.
In the case when no statements in the try block throw an exception, then all catch blocks are skipped and execution continues with the next statement following the try-catch statement.
If any one of the statements throws an exception, the statements in the matching catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
Here's how the control flows when there are multiple catch blocks.
In the case when no statements in the try block throw an exception, then all catch blocks are skipped and execution continues with the next statement following the try-catch statement.
If any one of the statements throws an exception, the statements in the matching catch block are executed. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
The finally block is not used often in introductory level programs, but we will introduce them here for the sake of complete coverage of the topic. For example, suppose we open a communication channel from our Java program to a remote web server to exchange data. If the data exchange is successfully completed in the try block, then we close the communication channel and finish the operation. If the data exchange is interrupted for some reason, an exception is thrown and the operation is aborted. In this case also, we need to close the communication channel, because leaving the channel open by one application blocks other applications from using it. The code to close the communication channel should therefore be placed in the finally block.
Here's how the control flows when there are multiple catch blocks and the finally block.
In the case when no statements in the try block throw an exception, then all catch blocks are skipped, but the statements in the finally block are executed. Execution continues with the next statement following the try-catch statement.
If any one of the statements throws an exception, the statements in the matching catch block are executed first and the statements in the finally block are executed next. Execution then continues to the statement following the try-catch statement, ignoring any remaining statements in the try block.
Using the try-catch statement is the first way to handle the exceptions. The second way is to propagate the thrown exception back to the caller of the method. The method that includes the statement that calls our method must either catch it or propagate it back to their caller.
It is possible to throw an exception from our own method.
We say a method throws an exception directly when the method includes the throw statement. Otherwise, a method is throwing an exception indirectly.
This illustration shows a sequence of method calls among the exception throwers.
Method D throws an instance of Exception. The green arrows indicate the direction of calls. The red arrows show the reversing of call sequence, looking for a matching catcher. Method B is the catcher.
The call sequence is traced by using a stack.
Callers of a method that can throw a checked exception must include the try-catch statement in the method body or the throws clause in the header.
It is optional for callers of a method that can throw runtime exceptions to include the try-catch statement in the method body or the throws clause in the header.