SE_21_Lesson_13: Exceptions, Enums and Memory

-> Exception olanda kod davam elemir

package org.example.part4;

public class Main {
public static void main(String[] args) {
System.out.println("Start");
System.out.println(5 / 0);
System.out.println("Continue...");
}

} 


-> try catch bloku

package org.example.part4;

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Start");
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();
try {
System.out.println(a /
b);
} catch (Exception e) {
// if exception happens trigger this block
System.out.println("Something went wrong");
}
System.out.println("Continue...");
}
}


-> Oz Exception klasimizi yaratmaq

package org.example.part4;

public class MyException extends Exception {

public MyException(String message) {
super(message);
}
}


-> Multiple catch bloku

package org.example.part4;

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Start");
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();

try {
System.out.println(a / b);
} catch (ArithmeticException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}


-> Bir nece exception-u bir blokda tutmaq

package org.example.part4;

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Start");
Scanner in = new Scanner(System.in);
int a = in.nextInt();
int b = in.nextInt();

try {
System.out.println(a / b);
} catch (ArithmeticException | NullPointerException | ArrayIndexOutOfBoundsException e) {
e.printStackTrace();
}
}
}


-> RuntimeException & Non RuntimeException. Checked & Unchecked exceptions

1. Unchecked Exception. RuntimeException

package org.example.part4;

public class MyException extends RuntimeException {

public MyException(String message) {
super(message);
}
}
package org.example.part4;

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Start");
throw new MyException("something went wrong");
System.out.println("Continue...");
System.out.println("End");
}
}


2. Checked exception. Non RuntimeException

package org.example.part4;

public class MyException extends Exception {

public MyException(String message) {
super(message);
}
}
package org.example.part4;

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
System.out.println("Start");
throw new MyException("something went wrong");
System.out.println("Continue...");
System.out.println("End");
}
}


-> Checked ve Unchecked exception-lar metodda

1. Unchecked

package org.example.part4;

public class MyException extends RuntimeException {

public MyException(String message) {
super(message);
}
}
package org.example.part4;

public class Main {
public static void main(String[] args) {
foo();
}

public static void foo() {
throw new MyException("exception");
}
}


2. Checked

package org.example.part4;

public class MyException extends Exception {

public MyException(String message) {
super(message);
}
}
package org.example.part4;

public class Main {
public static void main(String[] args) {
foo();
}

public static void foo() {
throw new MyException("exception");
}
}


-> Metodun icinde bir exception atmaq, lakin tutanda bashqa exception tutmaq

package org.example.part4;

import java.sql.SQLException;

public class Main {
public static void main(String[] args) throws SQLException {
foo();
}

public static void foo() throws Exception {
throw new SQLException("Can not connect to DB");
}
}

Lakin:

package org.example.part4;

import java.sql.SQLException;

public class Main {
public static void main(String[] args) throws Exception {
foo();
}

public static void foo() throws Exception {
throw new SQLException("Can not connect to DB");
}
}

Niye bele bash verir? Cunki polymorphisme gore SQLException bir Exceptiondur, demeli Exception teleb olunan yere SQLException gondermek olar. Lakin main metoddaki foo() metodunu cagirdiqda o anlamir ki ona gonderilen mehz SQLException -un obyektidir ona gorede problem yaradir.


-> Calishmaq lazimdir ki, Exception atmayaq, atdigimiz Exception daha spesifik olmalidir. (According to Joshua Block - Effecctive Java)

package org.example.part4;

import java.io.IOException;
import java.sql.SQLException;

public class Main {
public static void main(String[] args) {
try {
foo();
} catch (SQLException | IOException exception) {
exception.printStackTrace();
}
}

public static void foo() throws SQLException, IOException {
throw new IOException("Input Output Exception happened");
}
}

Bu zaman method signature-ye baxan developer aninda anlamalidir ki, metodda ne problem bash vere biler. Eksi oldugu halda Exception-un ne oldugunu anlamir.


-> @SneakyThrows (Lombok) annotation.

The @SneakyThrows annotation from Lombok allows you to throw checked exceptions without using the throws declaration. This comes in handy when you need to raise an exception from a method within very restrictive interfaces like Runnable.

@SneakyThrows
public static void bar() {
System.out.println("bla bla bla");
throw new Exception();
}




*** addition:

package com.appsdeveloperblog.lesson33;

import java.util.Random;

public class Main {
public static void main(String[] args) {
try {
riskyMethod1();
riskyMethod2();
riskyMethod3();
} catch (RuntimeException e) {
throw new RuntimeException("Something bad happened in main");
}
}

public static void riskyMethod1() {
Random random = new Random();
if (random.nextBoolean()) {
throw new RuntimeException("Something bad happened");
}
}

public static void riskyMethod2() {
Random random = new Random();
if (random.nextBoolean()) {
throw new RuntimeException("Something bad happened");
}
}

public static void riskyMethod3() {
Random random = new Random();
if (random.nextBoolean()) {
throw new RuntimeException("Something bad happened");
}
}

}


solution:

package com.appsdeveloperblog.lesson33;

import java.util.Random;

public class Main {
public static void main(String[] args) {
try {
riskyMethod1();
riskyMethod2();
riskyMethod3();
} catch (RuntimeException e) {
throw new RuntimeException("Something bad happened in main", e);
}
}

public static void riskyMethod1() {
Random random = new Random();
if (random.nextBoolean()) {
throw new RuntimeException("Something bad happened");
}
}

public static void riskyMethod2() {
Random random = new Random();
if (random.nextBoolean()) {
throw new RuntimeException("Something bad happened");
}
}

public static void riskyMethod3() {
Random random = new Random();
if (random.nextBoolean()) {
throw new RuntimeException("Something bad happened");
}
}

}



----------------------------------------------------------------------------------------------------------------------------------------------------------

-> Constructorsuz enumlar

package org.example;

public enum Operation {

SUM, SUBTRACT, MULTIPLY, DIVIDE, MODULUS
}

package org.example;

public class Main {
public static void main(String[] args) {
Operation operation = Operation.SUM;
System.out.println(operation);
System.out.println(operation.name());
System.out.println(operation.ordinal());
System.out.println(operation.toString());
}
}


-> Constructorlu enumlar

package org.example;

public enum Operation {
SUM('+'),
SUBTRACT('-'),
MULTIPLY('*'),
DIVIDE('/'),
MODULUS('%'),
DEFAULT();

private char c;

Operation() {
}

Operation(char c) {
this.c = c;
}

public char getC() {
return c;
}
}

package org.example;

public class Main {
public static void main(String[] args) {
Operation operation = Operation.SUM;
System.out.println(operation);
System.out.println(operation.name());
System.out.println(operation.ordinal());
System.out.println(operation.toString());
System.out.println(operation.getC());
}
}


-> Enumlarin ustunluyu

package org.example;

public enum Operation {
SUM('+'),
SUBTRACT('-'),
MULTIPLY('*'),
DIVIDE('/'),
MODULUS('%'),
DEFAULT();

private char c;

Operation() {
}

Operation(char c) {
this.c = c;
}

public char getC() {
return c;
}

public static Operation getOperation(char c) {
if (c == '+') return Operation.SUM;
else if (c == '-') return Operation.SUBTRACT;
else if (c == '*') return Operation.MULTIPLY;
else if (c == '/') return Operation.DIVIDE;
else if (c == '%') return Operation.MODULUS;
else return Operation.DEFAULT;
}
}
package org.example;

import java.util.Scanner;

public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
char c = in.nextLine().charAt(0);
Operation operation = Operation.getOperation(c);

}

public static Double calculate(Double a, Double b, Operation operation) {
if (operation == Operation.SUM) {
return a + b;
} else if (operation == Operation.SUBTRACT) {
return a - b;
} else if (operation == Operation.MULTIPLY) {
return a * b;
} else if (operation == Operation.DIVIDE) {
return a / b;
} else if (operation == Operation.MODULUS) {
return a % b;
} else return null;
}
}


-> Enumlar arxa planda nece ishleyir

package enums;

public final class Operation2 {

public static final Operation2 SUM = new Operation2('+');
public static final Operation2 SUBTRACT = new Operation2('-');
public static final Operation2 MULTIPLY = new Operation2('*');
public static final Operation2 DIVIDE = new Operation2('/');
public static final Operation2 DEFAULT = new Operation2();

private char c;

private Operation2() {
}

private Operation2(char c) {
this.c = c;
}

public char getC() {
return c;
}

}
package org.example;

public class Main2 {
public static void main(String[] args) {
Operation operation = Operation.SUM;
Operation2 operation2 = Operation2.SUM;
}
}



-> Some examples:

package org.example.part5;

public enum Numbers {
ZERO(0, "Sifir", "Zero"),
ONE(1, "Bir", "One"),
TWO(2, "Iki", "Two"),
THREE(3, "Uc", "Three"),
FOUR(4, "Dord", "Four"),
FIVE(5, "Besh", "Five"),
SIX(6, "Alti", "Six"),
SEVEN(7, "Yeddi", "Seven"),
EIGHT(8, "Sekkiz", "Eight"),
NINE(9, "Doqquz", "Nine"),
TEN(10, "On", "Ten"),
UNDEFINED;

private Integer value;
private String nameAze;
private String nameEng;

Numbers() {
}

Numbers(Integer value, String nameAze, String nameEng) {
this.value = value;
this.nameAze = nameAze;
this.nameEng = nameEng;
}

public Integer getValue() {
return value;
}

public String getNameAze() {
return nameAze;
}

public String getNameEng() {
return nameEng;
}

// public static Numbers getNumber(Integer number) {
// return Arrays.stream(Numbers.values())
// .filter(n -> n.getValue().equals(number))
// .findFirst()
// .orElse(Numbers.UNDEFINED);
// }

public static Numbers getNumber(Integer number) {
return number >= 0 && number < 11 ? Numbers.values()[number] : Numbers.UNDEFINED;
}
}


-----------------------------------------------------------------------------------------------------------------------------

 Heap - JVM terefinden obyekt yaratmaq ucun iwlenilen yaddaw yeridir. Buna dynamic memory area da deyilir. Normalda stack - dan daha boyukdur. 

Stack LIFO(last in first out) prinsipi ile iwleyir. Stack proqramda o anda caliwan, aktiv olan metodlar ucun ayrilan yaddawdir. main-den davam ederek, cagrilan her yeni metod ucun stackda uste yeni bir pencere acilir. Metod iwini bitirende, onu cagiran metoda qayidarken stack-daki pencereleride silir. Stack-daki yaddaw pencereleri onun ucun acilan metodun parametrlerini local deyiwenlerini saxlayir. One gore de local variable -larina stack variable deyilir. 


*** Bir variable eger obyektin bir hissesidirse yeni object variable - dirsa(field) bu zaman heap yaddawdadir. Yox eger local variable-dirsa stack yaddawdadir. 


Mes: 

Car car = new Car();

car.make = "Mercedes";

car.model = "C200";

int speed = car.speed;

Burada: speed, car - stackda yerlewir, Car obyekti ise heap yaddawdadir, hemcinin ona mensub olan make, model de heap da yerlewir. 

Obyektin hissesi olan instance varialbe-lar tipden asili deyil daima heapda olur. Local variable-lar tipden asili olmadan daima stack yaddawda olur. 


-----------------------------------------------------------------------------------------------------------------------------Application start olduqda klasslar haqqinda butun informasiya class loader terefinden metaspace yazilir. Metaspace Java memory-nin bir hissesidir. Java memory ozu 3 hisseye bolunur: stack, heap ve metaspace.  Class variable(static) saxlanilacaq metaspace-de. Eger primitiv variable - dirsa o zaman hem ozu hem deyeri metaspacede saxlanilacaq. Eger reference variable-dirsa o zaman variable ozu metaspace-de lakin deyeri heap yaddawda saxlanilacaq. 

-----------------------------------------------------------------------------------------------------------------------------






Metaspace.

Metodlarin kodlari, JVM-in klaslari yuklediyi metaspace deyilen yaddawda tutulur. 



-> How Garbage Collector works

package org.example;

public class Main {
public static void main(String[] args) {
Person one = new Person();
Person two = one;
one = null;
}
}

Is object one erased from heap? No. Because object two still refers to the same object.

To prove it we write:

package org.example;

public class Person {
@Override
protected void finalize() throws Throwable {
System.out.println("Person is erased");
}
}
package org.example;

public class Main {
public static void main(String[] args) {
Person one = new Person();
Person two = one;
one = null;
System.gc();
}
}


package org.example;

public class Main {
public static void main(String[] args) {
Person one = new Person();
// Person two = one;
one = null;
System.gc();
}
}


Комментарии

Популярные сообщения из этого блога

IoC:ApplicationContext, BeanFactory. Bean

Lesson1: JDK, JVM, JRE

Lesson_2: Operations in Java