Oracle Academy Java Programming 3-6: Exceptions and Assertions Lesson PowerPoint
ID: 3853261 • Letter: O
Question
Oracle Academy
Java Programming 3-6: Exceptions and Assertions
Lesson PowerPoint - https://drive.google.com/open?id=0B3GMuhuuq6eANFl4ZEttWFFCM00
1. You would like to write a program that will open a file called “myFile.txt”. Write a try catch statement to open the file and catch the error if the file fails to open.
2. Create an exception called “myException” that prints out an error message when thrown.
3. Create a block of code that utilizes all three types of invariants and asserts their values.
Explanation / Answer
CODE TO QUESTION 1:open a file.
import java.io.File;
import java.io.*;
import java.awt.Desktop;
class papa{
public static void main(String[]args){
if(Desktop.isDesktopSupported())
{
try{
File txt = new File("hello.txt");//place full path of myfile.txt here
Desktop.getDesktop().open(txt);
}
catch(IOException ex)
{
}
}
}
}
Code to Question 2:
//creating my own exception
class MyException extends Exception{
MyException(String s){
super(s);
}
}
class ExceptionClass{
static void validate(int age)throws MyException{
if(age<18)
throw new MyException("not valid"); //using my Exception
else
System.out.println("welcome to vote");
}
public static void main(String args[]){
try{
validate(13);
}catch(Exception m){System.out.println("Exception occured: "+m);}
System.out.println("rest of the code...");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.